Why is adding null to a string legal?

前端 未结 5 536
旧巷少年郎
旧巷少年郎 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

    Conceptually, strings are normally thought of as values as opposed to references to objects which have identity. One of the main reasons that they aren't structs with value semantics is because of the overhead that comes with copying-on-assignment. If strings were values they couldn't be nullable and so a null is just treated by the "+" operator as if it were an empty string (i.e., as if default(string) == "" just as default(int) == 0).

提交回复
热议问题