Why strings does not compare references?

后端 未结 5 1085
耶瑟儿~
耶瑟儿~ 2021-01-11 23:54

I know it is special case but why == between strings returns if their value equals and not when their reference equals. Does it have something to do with overlloading operat

相关标签:
5条回答
  • 2021-01-12 00:07

    The == operator is overloaded in String to perform value equality instead of reference equality, indeed. The idea is to make strings more friendly to the programmer and to avoid errors that arise when using reference equality to compare them (not too uncommon in Java, especially for beginners).

    So far I have never needed to compare strings by reference, to be honest. If you need to do it you can use object.ReferenceEquals().

    0 讨论(0)
  • 2021-01-12 00:07

    on a string, == compares by value

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

    In short, == on strings compares the strings by value, not by reference, because the C# specification says it should.

    0 讨论(0)
  • 2021-01-12 00:15

    Yes. From .NET Reflector here is the equality operator overloading of String class:

    public static bool operator ==(string a, string b)
    {
        return Equals(a, b);
    }
    
    0 讨论(0)
  • 2021-01-12 00:26

    The equality operators (== and !=) are defined to compare the values of string objects, not references.

    There was not any situation in which I had to compare the references but if you want to do so then you can use:

    object.ReferenceEquals().
    
    0 讨论(0)
  • 2021-01-12 00:28

    Because strings are immutable and the runtime may choose to put any two strings with the same content together into the same reference. So reference-comparing strings doesn't really make any sense.

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