I was surprised to see an example of a string being initialised to null and then having something appended to it in a production environment. It just smelt wrong.
I was sure it would have thrown a null object exception but this greatly reduced example also works:
string sample = null;
sample += "test";
// sample equals "test"
*Note the original code I found sets a string property to null and appends to it elsewhere so answers involving the compiler optimizing out the null at compile-time are irrelevant.
Can someone explain why this works without error?
Follow-up:
Based on Leppie’s answer I used Reflector to see what is inside string.Concat. It is now really obvious why that conversion takes place (no magic at all):
public static string Concat(string str0, string str1)
{
if (IsNullOrEmpty(str0))
{
if (IsNullOrEmpty(str1))
{
return Empty;
}
return str1;
}
if (IsNullOrEmpty(str1))
{
return str0;
}
int length = str0.Length;
string dest = FastAllocateString(length + str1.Length);
FillStringChecked(dest, 0, str0);
FillStringChecked(dest, length, str1);
return dest;
}
**Note: the specific implementation I was investigating (in the .Net library by Microsoft) does not convert to empty strings as is suggested by the C# standards and most of the answers, but uses a few tests to shortcut the process. The end result is the same as if it did but there you go 🙂
the
+operator for strings are just shorthand forstring.Concatwhich simply turnsnullarguments into empty strings before the concatenation.Update:
The generalized version of string.Concat: