Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it Valid to Concatenate Null Strings but not to Call "null.ToString()"?

Tags:

string

c#

.net

null

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?

like image 242
superlogical Avatar asked May 30 '12 10:05

superlogical


People also ask

What happens if you call ToString on null?

.ToString() It will not handle NULL values; it will throw a NULL reference exception error.

Can you concatenate a string with null?

Using the String.concat() method is a good choice when we want to concatenate String objects. The empty String returned by the getNonNullString() method gets concatenated to the result, thus ignoring the null objects.

Can we concatenate null values?

Concatenating Data When There Are NULL ValuesTo resolve the NULL values in string concatenation, we can use the ISNULL() function. In the below query, the ISNULL() function checks an individual column and if it is NULL, it replaces it with a space.

What happens when concatenating strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.


1 Answers

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.

like image 128
Pranay Rana Avatar answered Sep 24 '22 07:09

Pranay Rana