Skip to content

Equals and GetHashCode

Question

Describe Equals and GetHashCode. Is there any correlation between these methods?

Short interview answer

Equals determines equality; GetHashCode provides a hash used by hash-based collections. Equal objects must return the same hash code, but unequal objects may collide.

Detailed answer

When overriding value equality, override both methods consistently or implement IEquatable<T>. Dictionary<TKey, TValue> and HashSet<T> use hash codes to locate candidates and then equality to confirm a match:

var key = new CustomerId("42");
var customers = new Dictionary<CustomerId, string> { [key] = "Ada" };

customers.TryGetValue(new CustomerId("42"), out var name); // Works only when both equality and hash code agree.

A hash code must remain stable while an object is used as a key. If CustomerId exposed a mutable field that participated in equality and changed after insertion, the dictionary could no longer find the entry in the expected bucket.

Sources