Advertisement
Advanced C#, Equality: Equals, GetHashCode & IEquatable

Why is it critical that GetHashCode() only depend on IMMUTABLE fields, and what bug occurs if you violate this rule?

Short answer

If an object's hash code can CHANGE after it's inserted into a hash-based collection (Dictionary, HashSet) because it depends on a mutable field, the collection can no longer find the object in its correct bucket — the object effectively becomes 'lost' in the collection, even…

Save C# mock interview
Advertisement
AModel answer
If an object's hash code can CHANGE after it's inserted into a hash-based collection (Dictionary, HashSet) because it depends on a mutable field, the collection can no longer find the object in its correct bucket — the object effectively becomes 'lost' in the collection, even though .Contains() might still show it exists if you enumerate manually.
public class MutablePoint {
  public int X; // mutable field used in hashing -- dangerous!
  public override int GetHashCode() => X.GetHashCode();
}
var set = new HashSet<MutablePoint>();
var p = new MutablePoint { X = 1 };
set.Add(p);
p.X = 99; // mutated after insertion!
Console.WriteLine(set.Contains(p)); // False! -- 'lost' in the wrong bucket now
Real-world example
Debugging a mysterious bug where an object provably added to a HashSet or Dictionary key can no longer be found after some of its fields were later mutated.
Likely follow-ups
  • Why do many style guides recommend using immutable types (or records) specifically for Dictionary/HashSet keys?
Related topics