Pitfalls of Equality
February 16, 2008
Consider the fallowing example:
SomeClass class1 = new SomeClass();
SomeClass class2 = new SomeClass();
bool result = (class1 == class2);
Due to class1 and class2 are exactly the same, you should expect result == true. However, result is false. The reason is operator (==) actually compares references of the objects, rather the objects itself. In case you want to compare objects, override and/or use ‘Equals’ method. Some points of interest:
-
By default, Equals method calls to GetHashCode() method and then compares it.
-
string type is immutable, itĀ overrides == operator and inside it calls to actual string comparison.
-
Interlocked.CompareExchange method comparing objects by references (!!)
-
If anyone cares, in Java operator (==) works in same way
Entry Filed under: General C#. .
Trackback this post | Subscribe to the comments via RSS Feed