Equals and GetHashCode
Each implementation of
Equals must fulfil the following requirements:
- Reflexive: An object must equal itself.
- 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 as
- 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))returns
- 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
- Compatible with
Equals: If two objects are equal (meaning that
Equalsreturns true), then
GetHashCodemust 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.
Table Of Contents