skip to content

In C#, how do you key a Dictionary<TKey,TValue> or HashSet<T> by a class you cannot modify that only has reference equality?

level: middleimportance: should knowfreq 48%

answer

  1. what the default comparer falls back to
  2. a constructor parameter
  3. two methods that must agree
  4. fixed for the collection's lifetime

basics

~10 s

Write an IEqualityComparer<T> whose Equals and GetHashCode use the identifying fields and pass it to the Dictionary<TKey,TValue> or HashSet<T> constructor; every lookup then hashes and compares keys through it instead of reference equality.

solid answer

~40 s

With no `Equals` or `GetHashCode` override on a class, the default comparer, `EqualityComparer<TKey>.Default`, compares references, so a new `BinLabel` instance from a scanner never finds the entry stored under an earlier, equal-looking instance. You cannot add overrides to a type from another assembly, but the hashed collections take an `IEqualityComparer<T>` in their constructors: implement `Equals(T?, T?)` over the identifying fields and `GetHashCode(T)` over the same fields, with `HashCode.Combine` doing the mixing, then write `new Dictionary<BinLabel, int>(BinLabelComparer.Instance)`. The comparer is fixed for the collection's lifetime and visible through the get-only `Comparer` property; to re-key existing data, pass the old dictionary and the new comparer to the copy constructor. Sorted collections are different: they take an `IComparer<T>`.

code

csharp · 29 lines
csharp
// BinLabel comes from a scanner SDK you cannot change: no Equals or GetHashCode override.
var byReference = new Dictionary<BinLabel, int>();
byReference[new BinLabel("A", 1, 4)] = 12;
Console.WriteLine(byReference.ContainsKey(new BinLabel("A", 1, 4)));   // False: default comparer = reference equality

var byLocation = new Dictionary<BinLabel, int>(BinLabelComparer.Instance);
byLocation[new BinLabel("A", 1, 4)] = 12;
Console.WriteLine(byLocation.ContainsKey(new BinLabel("A", 1, 4)));    // True
Console.WriteLine(byLocation.Comparer.GetType().Name);                  // BinLabelComparer

var scanned = new HashSet<BinLabel>(BinLabelComparer.Instance) { new("A", 1, 4) };
Console.WriteLine(scanned.Add(new BinLabel("A", 1, 4)));               // False: already present

sealed class BinLabel(string aisle, int shelf, int slot)
{
    public string Aisle { get; } = aisle;
    public int Shelf { get; } = shelf;
    public int Slot { get; } = slot;
}

sealed class BinLabelComparer : IEqualityComparer<BinLabel>
{
    public static readonly BinLabelComparer Instance = new();
    public bool Equals(BinLabel? x, BinLabel? y) =>
        ReferenceEquals(x, y) ||
        (x is not null && y is not null &&
         x.Aisle == y.Aisle && x.Shelf == y.Shelf && x.Slot == y.Slot);
    public int GetHashCode(BinLabel bin) => HashCode.Combine(bin.Aisle, bin.Shelf, bin.Slot);
}

go deeper

for a junior

Recall that a class without Equals and GetHashCode overrides is compared by reference in a Dictionary or HashSet, so a new but equal-looking object is a different key.

for a middle

Explain how to write an IEqualityComparer<T>, why Equals and GetHashCode must agree, and that the comparer is passed to the constructor and fixed for the collection's life.

for a senior

Diagnose lookups that miss on keys from another library, fix them without touching that library, and catch comparers whose hash reads fields their Equals ignores.

for a principal

Prefer one shared, stateless comparer per key type so every collection in the codebase agrees on identity, and require sets combined with each other to share it.

## Why the default comparer misses Every hashed collection in .NET, `Dictionary<TKey,TValue>`, `HashSet<T>` and `OrderedDictionary<TKey,TValue>` among them, finds an element in two steps: hash it to choose a bucket, then confirm a match with an equality test. Both steps go through an **equality comparer**, an object implementing `IEqualityComparer<T>` with two methods, `bool Equals(T? x, T? y)` and `int GetHashCode(T obj)`. When you pass no comparer, the collection uses `EqualityComparer<T>.Default`. That comparer calls the type's own `IEquatable<T>.Equals` if it has one, otherwise `object.Equals`, and the matching `GetHashCode`. For a class that overrides none of them, both fall back to **reference identity**: two objects are equal only if they are the same object. Picture a scanner SDK that returns a fresh `BinLabel` object with `Aisle`, `Shelf` and `Slot` properties on every scan. Store stock under one instance, scan the same bin again, and `ContainsKey` returns `false` because the new object is a different reference. Overriding `Equals` and `GetHashCode` is the type author's fix, covered in the lesson on equality and hashing; when the type is sealed, belongs to another assembly, or already defines equality differently, you supply the rule from outside instead. ## Supplying the rule from outside 1. Write a class that implements `IEqualityComparer<BinLabel>`. 2. In `Equals`, return `true` for the same reference, `false` if exactly one side is `null`, and otherwise compare the identifying fields. 3. In `GetHashCode`, combine the same fields, for example `HashCode.Combine(bin.Aisle, bin.Shelf, bin.Slot)`. 4. Pass one shared instance to each collection's constructor: `new Dictionary<BinLabel, int>(BinLabelComparer.Instance)` or `new HashSet<BinLabel>(BinLabelComparer.Instance)`. From then on the collection never calls `BinLabel`'s own methods. The comparer is stored when the collection is built and exposed through the read-only `Comparer` property; there is no setter, because every stored entry's bucket was computed with it. ## Writing the two methods well - Start `Equals` with `ReferenceEquals(x, y)`, which handles the same object and two `null`s at once, then reject a single `null` before reading any property. - Compare exactly the fields that define identity for your domain. For a bin label that is aisle, shelf and slot; a printed description or a scan timestamp is not part of identity. - Build `GetHashCode` with `HashCode.Combine`, which mixes the field hashes well. Its seed is chosen randomly per process, so the numbers differ between runs: never store them in a file or database, and never rely on them in tests. - Make the comparer a sealed class with a single static instance. It holds no state, and one instance lets code compare `dictionary.Comparer` against it when checking how a collection was built. ## The contract the comparer must keep - **Equal means equal hash.** If `Equals(x, y)` is `true`, `GetHashCode(x)` must equal `GetHashCode(y)`. Hashing a field that `Equals` ignores breaks this: equal keys land in different buckets, lookups miss and duplicates are stored. Hashing a subset of the compared fields is legal, just less selective. - **Stable answers.** A key's hash must not change while it is in the collection, so the fields the comparer reads should not change after insertion. - **Nulls.** `Dictionary<TKey,TValue>` rejects `null` keys before calling the comparer. `HashSet<T>` allows one `null` element and assigns it hash code `0` itself, but your `Equals` still receives `null` arguments and must handle them. - **Consistency across collections.** Two `HashSet<T>` instances built with different comparers can disagree. Set methods such as `IntersectWith` judge membership with the receiving set's comparer, and skip their fast path when the two comparers differ. ## Where comparers plug in | Collection | Takes | Used for | |---|---|---| | `Dictionary<TKey,TValue>` | `IEqualityComparer<TKey>` | hashing and matching keys | | `HashSet<T>` | `IEqualityComparer<T>` | hashing and matching elements | | `OrderedDictionary<TKey,TValue>` (.NET 9) | `IEqualityComparer<TKey>` | hashing and matching keys | | `SortedDictionary<TKey,TValue>`, `SortedList<TKey,TValue>` | `IComparer<TKey>` | ordering keys; no hashing at all | String keys are the most common case of all, and `StringComparer` already implements the interface; choosing among its options belongs to the material on string comparison. ## Re-keying and other pitfalls - To change the rule for existing data, copy it: `new Dictionary<BinLabel, int>(oldDictionary, BinLabelComparer.Instance)` rehashes every entry under the new comparer. `HashSet<T>` has the matching `(IEnumerable<T>, IEqualityComparer<T>)` constructor. - Copies do not inherit the comparer. `new Dictionary<TKey,TValue>(existing)` and `new HashSet<T>(existing)` use the default comparer unless you pass `existing.Comparer`, so a copy of a field-compared set quietly reverts to reference equality. - Subclassing the vendor type does not help when the vendor's library creates the instances you receive. - Keep the comparer stateless and share one instance; a comparer that reads mutable configuration can change its answers under a populated collection.

  • What breaks if the comparer's GetHashCode includes a field its Equals ignores?
    Two keys that `Equals` calls equal can produce different hash codes, so they land in different buckets. A lookup searches only its own bucket and misses, and the collection happily stores both as separate entries. Hash only fields that `Equals` compares; a subset is fine.
  • Can you change a Dictionary<TKey,TValue>'s comparer after construction?
    No. `Comparer` is get-only, because every stored entry was bucketed with the original comparer's hash codes. Build a new dictionary with the copy constructor, `new Dictionary<TKey,TValue>(old, newComparer)`, which rehashes each entry under the new rule.
  • Why can IntersectWith give different results depending on which HashSet<T> you call it on?
    The receiving set's comparer decides membership. If one set uses a field comparer and the other reference equality, calling it on the field-comparer set matches equal-looking labels, while calling it on the reference set keeps only shared instances. Give both sets the same comparer.

  • A comparer needs only Equals; its GetHashCode can return arbitrary values.
  • The dictionary's comparer can be swapped later through the Comparer property.
  • SortedDictionary takes the same IEqualityComparer<T> as Dictionary does.
  • Subclassing the vendor class fixes lookups for objects the vendor library creates.
  • Without overrides, the default comparer compares a class's fields one by one.
  • new Dictionary<TKey,TValue>(existing) keeps the comparer the original was built with.