Why is it Valid to Concatenate Null Strings but not to Call "null.ToString()"?
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?
Solution 1:
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
returnsnull
, 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.
Solution 2:
Because the +
operator in C# internally translates to String.Concat
, which is a static method. And this method happens to treat null
like an empty string. If you look at the source of String.Concat
in Reflector, you'll see it:
// while looping through the parameters
strArray[i] = (str == null) ? Empty : str;
// then concatenate that string array
(MSDN mentions it, too: http://msdn.microsoft.com/en-us/library/k9c94ey1.aspx)
On the other hand, ToString()
is an instance method, which you cannot call on null
(what type should be used for null
?).
Solution 3:
The first sample will be translated into:
var bob = String.Concat("abc123", null, null, null, "abs123");
The Concat
method checks input and translate null as an empty string
The second sample will be translated into:
var wtf = ((object)null).ToString();
So a null
reference exception will be generated here
Solution 4:
The first part of your code is just treated like that in String.Concat
,
which is what the C# compiler calls when you add strings. "abc" + null
gets translated to String.Concat("abc", null)
,
and internally, that method replaces null
with String.Empty
. So, that's why your first part of code does not throw any exception. it is just like
var bob = "abc" + string.Empty + string.Empty + string.Empty + "123"; //abc123
And in 2nd part of your code throws exception because 'null' is not an object, 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.
And 'ToString()
' is a method that can be called by an instance of an object but not any literal.