skip to content

In C#, why do two equal items both stay in a HashSet<T> when their class overrides Equals but not GetHashCode, and what is the fix?

level: middleimportance: must knowfreq 78%

answer

  1. hash first, Equals second
  2. Object.GetHashCode is per instance
  3. warning CS0659
  4. HashCode.Combine over the same fields

basics

~20 s

HashSet<T> compares stored hash codes before it calls Equals, and the inherited Object.GetHashCode gives each object its own hash, so equal items rarely meet. Override GetHashCode over the same fields Equals uses, typically with HashCode.Combine.

solid answer

~40 s

`HashSet<T>` and `Dictionary<TKey,TValue>` use `EqualityComparer<T>.Default`, which hashes the item first and calls `Equals` only on an entry in the same bucket whose stored hash code matches. If the class overrides `Equals(object)` but not `GetHashCode`, it inherits `Object.GetHashCode`, an identity-based value from `RuntimeHelpers.GetHashCode`, so two equal line items almost never get the same hash and `Equals` is never asked. The compiler warns about exactly this: CS0659, "overrides Object.Equals(object o) but does not override Object.GetHashCode()". The fix is `public override int GetHashCode() => HashCode.Combine(Sku, Quantity);` over the same members `Equals` compares, and those members must not change while the object sits in a set.

code

csharp · 18 lines
csharp
var cart = new HashSet<LineItem>
{
    new LineItem("SKU-42", 2),
    new LineItem("SKU-42", 2), // "equal" to the first
};
Console.WriteLine(cart.Count);                                   // 2
Console.WriteLine(cart.Contains(new LineItem("SKU-42", 2)));     // almost always False
Console.WriteLine(new LineItem("SKU-42", 2).Equals(new LineItem("SKU-42", 2))); // True

class LineItem // warning CS0659
{
    public LineItem(string sku, int quantity) { Sku = sku; Quantity = quantity; }
    public string Sku { get; }
    public int Quantity { get; }

    public override bool Equals(object? obj) =>
        obj is LineItem other && Sku == other.Sku && Quantity == other.Quantity;
}

go deeper

for a junior

Remember the pairing rule: override Equals and you must override GetHashCode over the same fields, or hashed collections such as HashSet<T> and Dictionary<TKey,TValue> stop finding equal items.

for a middle

Walk through the lookup: hash, bucket, stored hash comparison, then Equals. Name CS0659, explain what Object.GetHashCode returns, and write a HashCode.Combine implementation on the spot.

for a senior

Talk about failure modes in production: silent duplicates, cache misses, hash codes persisted across processes, and members that change while the object is a key. Treat CS0659 as a build error in your projects.

for a principal

Argue for a team default: value-like types get equality from the compiler where possible, hand-written equality is reviewed as a pair, and equality warnings are errors so the contract cannot drift.

## The contract between Equals and GetHashCode .NET's hashed collections rest on one rule: **if `a.Equals(b)` is true, `a.GetHashCode()` must equal `b.GetHashCode()`**. The reverse is not required; two unequal objects may share a hash (a **collision**), which only costs a little speed. A type that changes what `Equals` means without changing `GetHashCode` breaks the rule, and the collections fail silently rather than throwing. `System.Object` supplies both members: - `Object.Equals(object?)` returns `this == obj`, a reference comparison. - `Object.GetHashCode()` returns `RuntimeHelpers.GetHashCode(this)`, a value tied to the object instance, not its data. Override only `Equals` and the two disagree: two separate `LineItem("SKU-42", 2)` objects are now equal, yet each keeps its own instance-based hash. ## How HashSet<T> uses the two members When a `HashSet<T>` or `Dictionary<TKey,TValue>` is created without a comparer, it uses `EqualityComparer<T>.Default`. Adding an item then runs these steps: 1. Compute the item's hash code with `GetHashCode`. 2. Map the hash to a **bucket** (an index in an internal array). 3. Walk the entries in that bucket. For each, compare the **stored hash code** with the new one, and only when they match call `Equals`. 4. If no entry matched, store the item together with its hash code. With the inherited `GetHashCode`, step 3 almost never reaches `Equals` for the second line item, so the set stores both. `Contains(new LineItem("SKU-42", 2))` returns `false` for the same reason, while calling `Equals` directly returns `true`. Nothing throws, so the bug surfaces later as a duplicate cart line or a cache miss. ## The compiler already told you The C# compiler reports **CS0659**: "'LineItem' overrides Object.Equals(object o) but does not override Object.GetHashCode()". It is a warning, so the build succeeds; teams that enable `TreatWarningsAsErrors` turn it into a failed build. Its siblings cover operators: CS0660 and CS0661 fire when a type declares `operator ==` without overriding `Equals` or `GetHashCode`. ## Writing GetHashCode correctly - **Use the same members as `Equals`**, or a subset of them. Including a member that `Equals` ignores (a `Price` that is not part of identity) breaks the rule, because two equal objects could then hash differently. - **Use `HashCode.Combine`**. `System.HashCode` has `Combine` overloads for one to eight values and an `Add` method plus `ToHashCode()` for more. It calls each value's own `GetHashCode` and treats `null` as 0, so no null checks are needed. - **Keep the members stable** while the object is in a set or used as a dictionary key; a member that changes after insertion makes the entry unfindable. - **Do not persist hash codes.** `HashCode` mixes in a random seed generated once per process, and `string.GetHashCode` is randomized per process too, so the same data hashes differently on the next run. Hash codes are for in-memory lookups, never for files, databases or network messages. - **Do not compare `HashCode` instances.** `HashCode.Equals` and `HashCode.GetHashCode` are marked obsolete as errors; call `ToHashCode()` instead. | GetHashCode body | Equals compares Sku and Quantity | Verdict | |---|---|---| | `HashCode.Combine(Sku, Quantity)` | same members | correct | | `Sku.GetHashCode()` | subset | correct, more collisions | | `HashCode.Combine(Sku, Quantity, Price)` | extra member | breaks the contract | | inherited `Object.GetHashCode()` | none of them | breaks the contract | ## Checking an implementation in review - Does every member read by `Equals` appear in `GetHashCode`, or is it left out on purpose, and does `GetHashCode` read nothing that `Equals` ignores? - Does `Equals(object)` return `false` for `null` and for objects of other types instead of throwing? - Are the hashed members get-only or `init`-only, so the hash cannot drift while the object is stored in a set? - Is CS0659 visible in the build output, or hidden by `#pragma warning disable`? A suppression here needs a comment that explains why the inherited hash is acceptable. ## Where this sits among related lessons The language-neutral reason hashing needs equality is covered in the foundations material on hash tables. Supplying a separate equality for one collection (an `IEqualityComparer<T>` passed to the constructor) is covered with dictionaries and sets, and records generate both members for you, which the records material covers. Here the point is C#'s own mechanics: what `Object` gives you, what `EqualityComparer<T>.Default` calls, what CS0659 means and how `HashCode.Combine` closes the gap.

  • Is `public override int GetHashCode() => 0;` a correct implementation?
    It satisfies the contract, because equal objects always share the hash, so `HashSet<T>` and `Dictionary<TKey,TValue>` return correct answers. But every item lands in one bucket, so each lookup compares against every entry and becomes linear in the collection's size. It is a debugging trick, not a fix; hash the members `Equals` compares.
  • Why must a type never store the value returned by `HashCode.Combine` in a database?
    `System.HashCode` mixes in a seed generated randomly once per process, and `string.GetHashCode` is randomized per process too. The same `Sku` and `Quantity` therefore produce a different hash in the next process, so a stored value cannot be matched later. Persist a stable key, or a hash from a defined algorithm such as SHA-256 over a canonical encoding.

  • HashSet<T> calls Equals on every item, so GetHashCode only affects speed
  • Including an extra field in GetHashCode makes the hash more precise and is always safe
  • CS0659 is an error that stops the build
  • Hash codes from HashCode.Combine are stable across runs and can be stored
  • Two unequal objects must never return the same hash code