title: How does appending to a null string work in C#?
body: <p>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.</p>
  
  <p>I was sure it would have thrown a null object exception but this greatly reduced example also works:</p>
  
  <pre><code>string sample = null;
  sample += "test";
  // sample equals "test"
  </code></pre>
  
  <p>*<em>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.</em></p>
  
  <p>Can someone explain why this works without error?</p>
  
  <h2>Follow-up:</h2>
  
  <p>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):</p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <p>**<em>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 :)</em></p>