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 operators?
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()
.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With