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

后端 未结 4 507
陌清茗
陌清茗 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条回答
  •  情深已故
    2021-02-05 00:45

    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

提交回复
热议问题