I have a condition in a silverlight application that compares 2 strings, for some reason when I use ==
it returns false while .Equals()>
==
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.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