Two different “strings” are the same object instance?

前端 未结 3 835
天命终不由人
天命终不由人 2020-11-30 11:11

The code is pretty self explanatory. I expected when I made a1 and b1 that I was creating two different string instances that contain the same text

相关标签:
3条回答
  • 2020-11-30 11:46

    Compiler optimization. Simple as that.

    0 讨论(0)
  • 2020-11-30 11:51

    Literal string objects are coalesced into single instances by the compiler. This is actually required by the specification:

    Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (Section 7.9.7) appear in the same assembly, these string literals refer to the same string instance.

    0 讨论(0)
  • 2020-11-30 11:52

    The compiler is optimized to that the if string literals are equal with "==" operator than it does not need to create a new instance and both refer to the same instance... So, that's why your first part of question answered True.

    Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:

    string a = "hello";
    string b = "h";
    // Append to contents of 'b'
    b += "ello";
    Console.WriteLine(a == b);
    Console.WriteLine((object)a == (object)b);
    

    This displays "True" and then "False" because the content of the strings are equivalent, but a and b do not refer to the same string instance.

    The + operator concatenates strings:

    string a = "good " + "morning";
    

    This creates a string object that contains "good morning".

    Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

    string b = "h";
    b += "ello";
    

    for more reference check this on msdn and this

    0 讨论(0)
提交回复
热议问题