Equals and GetHashCode
suggest changeEach implementation of Equals must fulfil the following requirements:
- Reflexive: An object must equal itself.
x.Equals(x)returnstrue. - Symmetric: There is no difference if I compare x to y or y to x - the result is the same.
x.Equals(y)returns the same value asy.Equals(x). - Transitive: If one object is equal to another object and this one is equal to a third one, the first has to be equal to the third.if
(x.Equals(y) && y.Equals(z))returnstrue, thenx.Equals(z)returnstrue. - Consistent: If you compare an object to another multiple times, the result is always the same.Successive invocations of
x.Equals(y)return the same value as long as the objects referenced by x and y are not modified. - Comparison to null: No object is equal to
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 ==
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents