Why is adding null to a string legal?

前端 未结 5 534
旧巷少年郎
旧巷少年郎 2020-11-30 05:07

The MSDN article on String Basics shows this:

string str = \"hello\";
string nullStr = null;
string emptyStr = \"\";

string tempStr = str + nullStr; // temp         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 05:47

    From MSDN:

    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.

    More information on the + binary operator:

    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.

提交回复
热议问题