Why is adding null to a string legal?

前端 未结 5 540
旧巷少年郎
旧巷少年郎 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 06:09

    I agree that conceptually strings are just values. However, consider the following code:

    int? i = null;
    i += 1; // The result of this is that i == null
    

    If the other value type operators used default() the way the string operators are converting null to "", your explanation would make sense.

    It's simplest to say that the string operators are a shortcut (special case) for convenience.

提交回复
热议问题