I was surprised to see an example of a line initialized to zero, and then adding something to it in a production environment. He just cried wrong.
I was sure that this would throw an exception from the null object, but this very shorthand example also works:
string sample = null; sample += "test";
* Please note that the source code that I found sets the string property to null and is added to it elsewhere, so the answers related to the compiler optimizing zero at compile time do not matter.
Can someone explain why this works without errors?
Subsequent:
Based on Leppie's answer, I used Reflector to see what's inside the string. Concat. Now it’s really obvious why this transformation takes place (there is 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 studied (in the .Net library from Microsoft) does not convert to blank lines, as suggested by C # standards and most answers, but uses several tests to shorten the process, the end result is the same as if if he were, but there you go :)
Gone Coding Oct. 31 '11 at 12:10 2011-10-31 12:10
source share