How does appending to a null string work in C#?
the +
operator for strings are just shorthand for string.Concat
which simply turns null
arguments into empty strings before the concatenation.
Update:
The generalized version of string.Concat:
public static string Concat(params string[] values)
{
int num = 0;
if (values == null)
{
throw new ArgumentNullException("values");
}
string[] array = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
string text = values[i];
array[i] = ((text == null) ? string.Empty : text);
num += array[i].Length;
if (num < 0)
{
throw new OutOfMemoryException();
}
}
return string.ConcatArray(array, num);
}
The relevant citation should be ECMA-334 §14.7.4:
String concatenation:
string operator +(string x, string y); string operator +(string x, object y); string operator +(object x, string y);
The binary
+
operator performs string concatenation when one or both operands are of typestring
. If an operand of string concatenation isnull
, an empty string is substituted. Otherwise, any non-string operand is converted to its string representation by invoking the virtualToString
method inherited from typeobject
. IfToString
returnsnull
, an empty string is substituted.
it is because
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.
From How to: Concatenate Multiple Strings (C# Programming Guide)
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.
From Addition operator