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
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().
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.
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);
}
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().
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.