🔧 C#: Fix a Struct’s IEquatable Implementation Being Bypassed
Implementing IEquatable<T> on a struct gives a fast, allocation-free Equals(T other) — but C# requires you to ALSO override the inherited object.Equals(object) and GetHashCode() yourself for that optimization to apply everywhere. Any code path that compares the struct through its boxed object form — a non-generic collection, or a call through an object-typed parameter — falls back to the compiler-generated default, which reflects over every field one by one, ignoring your custom logic entirely, and can even produce a different result if your implementation was ever meant to skip a field the default comparison doesn’t know to skip.
🔎 The Problem
public struct CacheKey : IEquatable<CacheKey>
{
public string Id;
public DateTime FetchedAt; // intentionally ignored for equality
public bool Equals(CacheKey other) => Id == other.Id;
// no override of Equals(object) or GetHashCode() -> boxed comparisons
// fall back to ValueType.Equals, which compares BOTH fields including FetchedAt
}
✅ Fix: Override the Object-Level Methods Too
- Whenever a struct implements
IEquatable<T>, also explicitly overrideEquals(object obj)andGetHashCode()— the interface implementation alone does not automatically wire up the inherited object-level methods. - Add a unit test that specifically compares two instances through an
object-typed reference, since normal day-to-day code that always compares the struct through its concrete type will never exercise the boxed path at all. - If the struct intentionally excludes certain fields from equality, make sure that exclusion is implemented identically in
Equals(T other), theEquals(object)override, andGetHashCode().
🚨 Why This Is Dangerous
- Using the struct as a key in a plain
Dictionary<TKey, TValue>is usually fine since generic collections call theIEquatable<T>path directly — the danger is specifically older interop code, serialization logic, or any API acceptingobjectparameters without you realizing it bypasses your optimized implementation.
IEquatable<T> is an offer your struct makes to callers who ask for it by type — callers who only have an object in hand never see that offer at all.
