Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix a Mutable GetHashCode That Makes an Object Permanently Unfindable in a HashSet After It’s Already Inserted

- 15.10.26 - ErcanOPAK

đź”§ 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.Status reads 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.

— C# Best Practice

Related posts:

C#: Why Pattern Matching Against a Null Object Doesn't Throw, and Why That's Not Always Safe

C#: Why Pattern Matching Against a Null Object Doesn't Throw, and Why That's Not Always Safe

C# “Enum Flags” — The Powerful Feature 90% Underuse

C# “Enum Flags” — The Powerful Feature 90% Underuse

C# Async Code Still Causes High CPU

C# Async Code Still Causes High CPU

Views: 9

Post navigation

The AI Prompt That Turns a Room-by-Room Home Inventory Video or Photos Into a Single List You Can Hand to Your Insurer
Photoshop: Fix Camera Raw Filter Edits That Get Lost on Reopen Because They Were Applied Directly Instead of as a Smart Filter

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com