Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does string comparison == only work because strings are immutable?

Tags:

string

c#

.net

I had a thought before when comparing two strings with their variables:

string str1 = "foofoo";
string strFoo = "foo";
string str2 = strFoo + strFoo;

// Even thought str1 and str2 reference 2 different
//objects the following assertion is true.

Debug.Assert(str1 == str2);

Is this purely because the .NET runtime recognises the string's value is the same and because strings are immutable makes the reference of str2 equal to that of str1?

So when we do str1 == str2 we are actually comparing references and not the values? I originally thought this was the product of syntactic sugar, but was I being incorrect?

Any inaccuracies with what I've written?

like image 739
m.edmondson Avatar asked Jan 18 '12 16:01

m.edmondson


People also ask

Can == be used to compare strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

Why == does not work with string?

This is because the == operator doesn't check for equality. It checks for identity. In other words, it doesn't compares the String s value - it compares object references.

Why does == work on strings in Java?

The operator == checks identity of two objects (whether two variables refer to same object). Since str1 and str2 refer to same string in memory, they are identical to each other. The method equals checks equality of two objects (whether two objects have same content). Of course, the content of str1 and str2 are same.

Can we use == operator for strings?

Using the == operator compares the object reference. Using the equals() method compares the value of the String . The same rule will be applied to all objects. When using the new operator, a new String will be created in the String pool even if there is a String with the same value.


2 Answers

The answer is in the C# Spec §7.10.7

The string equality operators compare string values rather than string references. When two separate string instances contain the exact same sequence of characters, the values of the strings are equal, but the references are different. As described in §7.10.6, the reference type equality operators can be used to compare string references instead of string values.

like image 78
DaveShaw Avatar answered Oct 19 '22 08:10

DaveShaw


No.

== works because the String class overloads the == operator to be equivalent to the Equals method.

From Reflector:

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool operator ==(string a, string b)
{
    return Equals(a, b);
}
like image 42
Chris Shain Avatar answered Oct 19 '22 07:10

Chris Shain