Striter Alfa Striter Alfa - 3 months ago 13
C# Question

Why concatenating two null string results an empty string?

I just saw a weird result while I tried to concat two

null
strings: It returns an empty one! I can not imagine if it have some utility or why this occurs.

Example:

string sns = null;
sns = sns + sns;
// It results in a String.Empty

string snss = null;
snss = String.Concat(snss, snss);
// It results in a String.Empty too!


Can someone tell me why it returns a
String.Empty
instead null?

Answer

Here is a fragment from C# Language Specification, the “7.8.4 Addition operator” section:

String concatenation:

string operator +(string x, string y);
string operator +(string x, object y);
string operator +(object x, string y);

These overloads of the binary + operator perform string concatenation. 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.

Comments