đź”§ The Object That Disappeared Into Its Own HashSet
A HashSet<T> decides which bucket an item lives in at the moment it’s inserted, using GetHashCode() at that instant – it never recalculates the hash later. If the fields that feed GetHashCode() change after insertion, the object is still physically sitting in the collection, but Contains(), Remove(), and a fresh lookup all compute a different hash now and go looking in the wrong bucket entirely.
🔎 The Problem
public class Order
{
public string Status { get; set; }
public int Id { get; set; }
public override int GetHashCode() => Status.GetHashCode();
public override bool Equals(object obj) =>
obj is Order o && o.Status == Status && o.Id == Id;
}
var openOrders = new HashSet<Order>();
var order = new Order { Id = 42, Status = "Open" };
openOrders.Add(order);
// Later, the same reference, now mutated:
order.Status = "Shipped";
// The object is still physically inside the HashSet's
// internal array - but Contains() hashes it again using
// "Shipped" now, looks in a different bucket, and finds
// nothing there.
bool stillThere = openOrders.Contains(order); // false
âś… Fix: Keep Hash Code Inputs Immutable, or Key by Something That Never Changes
- Base GetHashCode() only on fields that are set once in the constructor and never reassigned – an immutable Id is a safe hash input, a mutable Status, Name, or any property with a public setter is not.
- If you need to look items up by a mutable field, use a Dictionary<TKey, TValue> keyed by a separate immutable identifier (the object’s Id) instead of hashing the mutable object itself – the lookup key never drifts out of sync with where the entry actually lives.
- If an object already in a HashSet must change, remove it first, mutate it, then re-add it – that forces a fresh hash computation at the moment it’s reinserted, which is the only time a HashSet ever looks at GetHashCode() again.
⚠️ Why This Is Easy to Miss
- A direct reference to the object still works fine –
order.Statusreads correctly, and the object prints normally. It’s specifically hash-bucket-based lookups (Contains, Remove, a second Add that should have deduplicated) that silently fail, so the bug only shows up as ‘this item I know is in the set says it isn’t.’ - It passes every test where you insert and immediately check – the gap only opens once something mutates the object in between, which in a real app is often a separate method, days later, written by someone who never saw the HashSet.
A HashSet remembers where it put something by the hash it had on the day it moved in – change that hash afterward, and the object still lives there, you just can’t find the door anymore.
