Equals and GetHashCode
suggest changeEach implementation of Equals must fulfil the following requirements:
- Reflexive: An object must equal itself.
x.Equals(x)returnstrue. - Symmetric: Comparing x to y gives the same result as comparing y to x.
x.Equals(y)returns the same value asy.Equals(x). - Transitive: If one object equals a second and the second equals a third, the first equals the third. If
(x.Equals(y) && y.Equals(z))returnstrue, thenx.Equals(z)returnstrue. - Consistent: Comparing the same objects twice gives the same result. Successive calls to
x.Equals(y)return the same value while x and y are unchanged. - Comparison to null: No object equals
null.x.Equals(null)returnsfalse.
Implementations of GetHashCode:
- Compatible with
Equals: If two objects are equal (meaning thatEqualsreturns true), thenGetHashCodemust return the same value for each of them. - Large range: If two objects are not equal (
Equalssays false), there should be a high probability their hash codes are distinct. Perfect hashing is often not possible as there is a limited number of values to choose from. - Cheap: It should be inexpensive to calculate the hash code in all cases.
See: Guidelines for Overloading Equals() and Operator ==
Writing a good GetHashCode override
Override Equals and GetHashCode on custom types
Equals and GetHashCode in IEqualityComparer
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents