Why should a C# struct used as a Dictionary key implement IEquatable<T>, and what must its Equals(object) and GetHashCode do alongside it?
answer
- which comparer Default picks
- Equals(object) needs an object
- one box per comparison
- three members, one definition
basics
~10 sEqualityComparer<T>.Default uses IEquatable<T>.Equals(T) when the struct implements it; otherwise it calls Equals(object), which boxes the key on every comparison. Equals(object) must forward to Equals(T), and GetHashCode must hash the same fields.
solid answer
~30 s`Dictionary<TKey,TValue>` compares keys through `EqualityComparer<TKey>.Default`. For a `TKey` that implements `IEquatable<TKey>`, that is `GenericEqualityComparer<T>`, which calls the strongly typed `Equals(T)` with no conversion. Otherwise it is `ObjectEqualityComparer<T>`, whose call binds to `Equals(object)`, so a struct argument is boxed into a new heap object on each comparison. On a hot path that is garbage per lookup. Implementing `IEquatable<T>` is not enough on its own: override `Equals(object)` to forward to `Equals(T)` (analyzer rule CA1067 asks for it) and override `GetHashCode` over the same fields, so every caller, typed or not, sees one definition of equality.
code
csharp · 36 linesusing System.Collections.Generic;
Console.WriteLine(EqualityComparer<PlainKey>.Default.GetType().Name);
Console.WriteLine(EqualityComparer<EquatableKey>.Default.GetType().Name);
var plain = new Dictionary<PlainKey, int> { [new PlainKey(42, 7)] = 1 };
var equatable = new Dictionary<EquatableKey, int> { [new EquatableKey(42, 7)] = 1 };
for (int round = 0; round < 3; round++)
{
long before = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < 100_000; i++) plain.ContainsKey(new PlainKey(42, 7));
long mid = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < 100_000; i++) equatable.ContainsKey(new EquatableKey(42, 7));
long after = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"round {round}: plain {mid - before} bytes, equatable {after - mid} bytes");
}
readonly struct PlainKey(int skuId, int warehouseId)
{
public int SkuId { get; } = skuId;
public int WarehouseId { get; } = warehouseId;
public override bool Equals(object? obj) =>
obj is PlainKey other && SkuId == other.SkuId && WarehouseId == other.WarehouseId;
public override int GetHashCode() => HashCode.Combine(SkuId, WarehouseId);
}
readonly struct EquatableKey(int skuId, int warehouseId) : IEquatable<EquatableKey>
{
public int SkuId { get; } = skuId;
public int WarehouseId { get; } = warehouseId;
public bool Equals(EquatableKey other) =>
SkuId == other.SkuId && WarehouseId == other.WarehouseId;
public override bool Equals(object? obj) => obj is EquatableKey other && Equals(other);
public override int GetHashCode() => HashCode.Combine(SkuId, WarehouseId);
}go deeper
Recall that IEquatable<T> adds a typed Equals(T) method and that a struct used as a key should implement it together with Equals(object) and GetHashCode.
Explain how EqualityComparer<T>.Default picks GenericEqualityComparer<T> or ObjectEqualityComparer<T>, where the box comes from, and how the three members forward to one definition.
Back the claim with a measurement such as allocated bytes per lookup, connect it to garbage collector pressure on hot paths, and use analyzer rules CA1066 and CA1067 to keep the members in step.
Decide where the rule applies: value types used as keys or in hot comparisons implement IEquatable<T> or become record structs, enforced by enabling the equality analyzer rules for the codebase.
## What IEquatable<T> is `System.IEquatable<T>` declares a single method, `bool Equals(T? other)`. Unlike `Object.Equals(object?)`, its parameter has the exact type, so the caller passes the value as it is. For a **value type** (a `struct`) that matters: converting a struct to `object` is **boxing**, which copies the value into a new heap object. The general mechanics of boxing are covered in the lesson on boxing and unboxing; here the point is which equality call boxes and how `IEquatable<T>` avoids it. ## How EqualityComparer<T>.Default chooses `Dictionary<TKey,TValue>`, `HashSet<T>`, `List<T>.Contains` and many LINQ operators compare items through `EqualityComparer<T>.Default` when no comparer is supplied. That property returns a comparer chosen once per type: | Key type | Comparer returned | Equality call it makes | |---|---|---| | implements `IEquatable<T>` | `GenericEqualityComparer<T>` | `Equals(T)`: no boxing | | does not | `ObjectEqualityComparer<T>` | `Equals(object)`: the argument is boxed | In the .NET 10 source, `ObjectEqualityComparer<T>.Equals(T x, T y)` calls `x.Equals(y)` with `T` unconstrained, so the call binds to `Equals(object)` and `y` is converted to `object`. In the snippet below, 100,000 `ContainsKey` calls on a plain struct key allocated 2,400,000 bytes, one 24-byte box per lookup, while the same lookups on an `IEquatable<T>` key allocated nothing. The exact figure depends on the struct's size; the box per comparison does not go away. ## The three members must agree Implementing the interface adds a second `Equals`. A correct value type then has three members that must describe one equality: 1. **`Equals(T other)`**: the real comparison of the fields that define identity. 2. **`override Equals(object? obj)`**: `obj is T other && Equals(other)`. Non-generic code, `object.Equals(a, b)` and any API that only knows `object` still call this one. 3. **`override GetHashCode()`**: `HashCode.Combine` over the same fields. What goes wrong when one is missing: - **No `Equals(object)` override.** Calls through `object` fall back to the inherited `ValueType.Equals`, which compares fields by its own rules and can disagree with your `Equals(T)`, for instance when your version ignores a cached field. The analyzer rule **CA1067** ("Override Equals when implementing IEquatable") reports this and is enabled as a suggestion in .NET 10. - **No `GetHashCode` override.** The compiler reports CS0659 when `Equals(object)` is overridden alone; the inherited `ValueType.GetHashCode` may not use the same fields as your `Equals`. - **The reverse case.** A struct that overrides `Equals(object)` without implementing the interface is flagged by **CA1066** ("Implement IEquatable when overriding Equals"), which is not enabled by default in .NET 10. ## Classes benefit less For a **class**, passing it as `object` is only a reference conversion, so nothing is boxed. `IEquatable<T>` still saves the type test and cast inside `Equals(object)` and documents value equality, but the gain is small. On an unsealed class it also invites the inheritance problem: a non-virtual `Equals(T)` dispatches on the declared type and can ignore a subclass's fields, which the lesson on equality across inheritance explores. ## When the box matters - **Hot lookups.** A dictionary probed per request or per loop iteration turns one box per comparison into steady work for the garbage collector. - **Collisions add more.** `Equals` runs for each entry in the bucket whose stored hash matches the probe, and each of those calls boxes when the comparer falls back to `Equals(object)`. - **Cold paths.** A dictionary built once at startup and read rarely gains little from the interface, but the three members must still agree, because correctness does not depend on traffic. - **Measure, then fix.** `GC.GetAllocatedBytesForCurrentThread()` around a loop of lookups, as in the snippet, is enough to see the box without a profiler. ## Practical checklist - Value-type keys: implement `IEquatable<T>`, make `Equals(T)` the single source of truth, forward `Equals(object)` to it, and hash the same fields. - Make the struct `readonly`: value-like keys should not change. Note that the dictionary stores its own copy of a struct key, so editing the caller's variable afterwards never alters the stored key; the mutable-key trap mostly concerns classes and reference-typed members. - Consider `operator ==` and `operator !=` delegating to `Equals(T)`; the compiler gives a struct no `==` of its own. - A `record struct` generates all of this, including `IEquatable<T>`; that generated code is covered with records. - Supplying a different equality for one dictionary through `IEqualityComparer<T>` belongs to the dictionaries material.
- Does the struct's own `GetHashCode` call box it inside a `Dictionary<TKey,TValue>`?Not when the struct overrides `GetHashCode`. The dictionary calls it on a `TKey` value through generic code, and the runtime can invoke the override directly on the value without boxing. The box in the non-`IEquatable<T>` case comes from passing the other key to `Equals(object)`, which needs an `object` argument.
- Why is `IEquatable<T>` declared invariant, with no `in` modifier on `T`?Equality across a hierarchy is fragile: if `IEquatable<Base>` could stand in for `IEquatable<Derived>`, a base-class comparison that ignores derived fields would be picked silently. The runtime source comments that the interface is invariant because of those questionable semantics around equality and inheritance.
- Implementing IEquatable<T> means Equals(object) no longer needs an override
- Dictionary<TKey,TValue> never boxes struct keys, whatever the key implements
- IEquatable<T> on a class avoids boxing just as it does on a struct
- EqualityComparer<T>.Default compares struct fields directly without calling Equals
- IEquatable<T> also supplies the hash code, so GetHashCode can stay inherited