Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why strings does not compare references?

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?

like image 861
Cocodrilo Avatar asked Mar 05 '11 13:03

Cocodrilo


3 Answers

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

like image 88
Joey Avatar answered Oct 14 '22 05:10

Joey


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.

like image 7
TToni Avatar answered Oct 14 '22 04:10

TToni


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);
}
like image 2
as-cii Avatar answered Oct 14 '22 04:10

as-cii