I have a condition in a silverlight application that compares 2 strings, for some reason when I use ==
it returns false while .Equals()
== Operator
.Equals
There is another dimension to an earlier answer by @BlueMonkMN. The additional dimension is that the answer to the @Drahcir's title question as it is stated also depends on how we arrived at the string
value. To illustrate:
string s1 = "test";
string s2 = "test";
string s3 = "test1".Substring(0, 4);
object s4 = s3;
string s5 = "te" + "st";
object s6 = s5;
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s2), s1 == s2, s1.Equals(s2));
Console.WriteLine("\n Case1 - A method changes the value:");
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s3), s1 == s3, s1.Equals(s3));
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s4), s1 == s4, s1.Equals(s4));
Console.WriteLine("\n Case2 - Having only literals allows to arrive at a literal:");
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s5), s1 == s5, s1.Equals(s5));
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s6), s1 == s6, s1.Equals(s6));
The output is:
True True True
Case1 - A method changes the value:
False True True
False False True
Case2 - Having only literals allows to arrive at a literal:
True True True
True True True
When we create any object there are two parts to the object one is the content and the other is reference to that content.
==
compares both content and reference;
equals()
compares only content
http://www.codeproject.com/Articles/584128/What-is-the-difference-between-equalsequals-and-Eq
==
and .Equals
are both dependent upon the behavior defined in the actual type and the actual type at the call site. Both are just methods / operators which can be overridden on any type and given any behavior the author so desires. In my experience, I find it's common for people to implement .Equals
on an object but neglect to implement operator ==
. This means that .Equals
will actually measure the equality of the values while ==
will measure whether or not they are the same reference.
When I'm working with a new type whose definition is in flux or writing generic algorithms, I find the best practice is the following
Object.ReferenceEquals
directly (not needed in the generic case)EqualityComparer<T>.Default
In some cases when I feel the usage of ==
is ambiguous I will explicitly use Object.Reference
equals in the code to remove the ambiguity.
Eric Lippert recently did a blog post on the subject of why there are 2 methods of equality in the CLR. It's worth the read
When ==
is used on an expression of type object
, it'll resolve to System.Object.ReferenceEquals.
Equals is just a virtual
method and behaves as such, so the overridden version will be used (which, for string
type compares the contents).