Friday, June 15, 2012

String concat with null

Source : My Higest Voted answer on StackOverflow
Question This is valid C# code
var bob = "abc" + null + null + null + "123";  // abc123
This is not valid C# code
var wtf = null.ToString(); // compiler error
Why is the first statement valid?

The reason for first one working:
From MSDN:
In string concatenation operations,the C# compiler treats a null string the same as an empty string, but it does not convert the value of the original null string.

More information on the + binary operator:

The binary + operator performs string concatenation when one or both operands are of type string.

If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual `ToString` method inherited from type object.

If ToString returns null, an empty string is substituted.

The reason of the error in second is:
null (C# Reference) - The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables.


  1. I've often though it would be great if Dot Net treated null as an object, so that null.ToString() would legally return null. Some languages do this.

    Oh well.

  2. The only hurdle to accessing this is of course human limitations and the fact that the brain does
    not function solely as a learning tool for the human being.
    I believe my exact words were "I don't want to be your dirty little secret. The food is decent and the drink specials on Tuesdays include $2.

    Review my web page; pub quiz area

  3. Some were practical, of course, but others were psychological and emotional.

    *Rounds table format. Her father, Bruce Paltrow,
    produced the critically acclaimed TV series
    that is considered the precursor to many medical shows today,

    Here is my web site free quiz Answer sheets

  4. The players would begin as members of the SCA, going to Phoenix for the Estrella War.

    The game was released on August 3, and is in stores now, but probably is where
    it will remain, sad to say. You Divide everyone at the party into two groups, or tribes.

    Also visit my blog post ... los angeles