How does appending to a null string work in C#?

后端 未结 4 613
陌清茗
陌清茗 2021-02-05 00:02

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

4条回答
  •  萌比男神i
    2021-02-05 00:32

    Here is what your code gets compiled to

    string sample = null;
    sample += "test";
    

    is compiled to this IL code:

    .entrypoint
      // Code size       16 (0x10)
      .maxstack  2
      .locals init ([0] string sample)
      IL_0000:  nop
      IL_0001:  ldnull
      IL_0002:  stloc.0
      IL_0003:  ldloc.0
      IL_0004:  ldstr      "test"
      IL_0009:  call       string [mscorlib]System.String::Concat(string,
                                                                  string)
      IL_000e:  stloc.0
      IL_000f:  ret
    

    And String.Concat takes care of NULL string.

提交回复
热议问题