C# Language Equals and GetHashCode

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

Each implementation of Equals must fulfil the following requirements:

  • Reflexive: An object must equal itself.
    x.Equals(x) returns true.

  • 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 y.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)) returns true, then x.Equals(z) returns true.

  • 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) returns false.

Implementations of GetHashCode:

  • Compatible with Equals: If two objects are equal (meaning that Equals returns true), then GetHashCode must return the same value for each of them.

  • Large range: If two objects are not equal (Equals says 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 ==



Got any C# Language Question?