codementor on Nostr: Learn: Never change a key while it is in a HashSet A HashSet or Dictionary files each ...
Learn: Never change a key while it is in a HashSet
A HashSet or Dictionary files each key by its hash code. If the key changes, its hash code changes, and the set looks in the wrong place.
```csharp
var p = new Point { X = 1 };
var set = new HashSet<Point> { p };
p.X = 2; // changes p's hash code
Console.WriteLine(set.Contains(p));
```
It prints False, even though p is in the set. Use keys that can't change, like strings, numbers or records without setters.
#tip · TIP-012
Published at
2026-11-21 13:37:42 UTCEvent JSON
{
"id": "7b52c179338c8bb176cfd9fa80a13f02eb31f9730405f39e68aa61d59ba4d31b",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1795268262,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: Never change a key while it is in a HashSet\n\nA HashSet or Dictionary files each key by its hash code. If the key changes, its hash code changes, and the set looks in the wrong place.\n\n```csharp\nvar p = new Point { X = 1 };\nvar set = new HashSet\u003cPoint\u003e { p };\np.X = 2; // changes p's hash code\nConsole.WriteLine(set.Contains(p));\n```\n\nIt prints False, even though p is in the set. Use keys that can't change, like strings, numbers or records without setters.\n\n#tip · TIP-012",
"sig": "2f29b24d73ad127f8e268ba550abe3a4963c10ab676f7c3e2ec73448c6e8d1aee9ab2154beff9ca984016c36c5a5459e819a077b26e8331b0fcdacd1635731ee"
}