posted on Wednesday, June 23, 2004 10:05 AM
by
leon
Identity vs Equivalence
Recent question triggered me to write this one.
When should we use == operator and when Object.Equals?
What if we need both Reference Identity and Object Instance Data Equivalence checks?
Those are usually very confusing questions. We have variety of methods to check reference equivalence and object identity in CLR with different semantics between Value and Reference types. If it is not enough, there are some historical problems with GetHashCode. Some of them you mentioned in your post. Worst, defined as Int32, hash code can not uniquely address more than 2^32 different objects. Ian Griffith just has excellent post here about it.
To make long story short, I will try to summarize identity/equivalence options we have in CLR:
Static Object.Equals - test for object equivalence.
Static Object.ReferenceEquals - test for object identity.
Operator == - defaults to identity test.
Object..GetHashCode – test for possibility of equivalence.
You can override Equals in derived type, but you will have to override GetHashCode also.
Best practices suggest overriding set of equivalence operators if you implement System.IComparable (see here). One reason for this is use of those operators in IList sorting internal implementation.
Some more information can be found in at dr GUI or this older discussion.