Why don't strings compare links?

I know this is a special case, but why == between the lines is returned if their value is equal, and not when their reference is equal. Does it have something in common with overload operators?

+6
operators string reference c #
source share
5 answers

The == operator is overloaded in String to perform equality of values ​​instead of referential equality. The idea is to make the strings more user-friendly to the programmer and avoid the errors that occur when using referential equality to compare them (not too rare in Java, especially for beginners).

Until now, I have never had to compare strings by reference, to be honest. If you need to do this, you can use object.ReferenceEquals() .

+13
source share

Since the lines are immutable, and the runtime can choose to place any two lines with the same content in the same link. Thus, links to string comparisons do not really make any sense.

+4
source share

in a line, == compares the value

"Although a string is a reference type, equality operators (== and! =) Are defined to compare the values ​​of string objects rather than links (7.9.7. String equality operators). This makes testing for string equality more intuitive."

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

+2
source share

Yes. From the .NET Reflector, the String class equality operator is overloaded here:

 public static bool operator ==(string a, string b) { return Equals(a, b); } 
+2
source share

Equality operators ( == and != ) Are defined to compare the values ​​of string objects, not references.

There was no situation in which I had to compare links, but if you want to do this, you can use:

 object.ReferenceEquals(). 
0
source share

All Articles