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