Back to results for “GetHashCode & IEquatable”
C# › Collections

How does Dictionary<TKey,TValue> handle hash collisions internally, and why does a poor GetHashCode() implementation degrade its performance?

Advanced

Answer

Dictionary<TKey,TValue> uses a hash table with SEPARATE CHAINING (or a similar bucket-based collision resolution) — when multiple keys hash to the same bucket, it falls back to a linear scan WITHIN that bucket using Equals(); a poorly-distributed GetHashCode() (e.g., one that always returns the same value) collapses the theoretical O(1) average lookup into effectively O(n), since every key lands in the same bucket.
public class BadKey {
  public override int GetHashCode() => 1; // terrible: every instance collides into the same bucket
}
// A Dictionary<BadKey, T> degrades to O(n) linear-scan performance
Real-world example Debugging a mysteriously slow Dictionary-based cache traced back to a custom key type with a poorly-implemented GetHashCode().

Common follow-ups: What's the contractual relationship that GetHashCode() and Equals() must maintain for a custom key type to work correctly?