codementor on Nostr: Learn: Hashing rules in C# Equal objects must have equal hash codes, so if you ...
Learn: Hashing rules in C#
Equal objects must have equal hash codes, so if you override Equals, override GetHashCode too. Records do both for you.
Don't read a missing key with dict[key]: it throws KeyNotFoundException. Use TryGetValue.
Lookups are O(1) on average, but O(n) in the worst case, when many keys collide.
```csharp
var ages = new Dictionary<string, int> { ["ann"] = 30 };
Console.WriteLine(ages.TryGetValue("bob", out int age) ? age : -1);
var set = new HashSet<Point> { new Point(1, 2) };
Console.WriteLine(set.Contains(new Point(1, 2)));
```
It prints -1 (no bob), then True (records compare by value).
Read more:
https://www.geeksforgeeks.org/dsa/hashing-data-structure/#tip · TIP-065
Published at
2026-10-27 08:37:51 UTCEvent JSON
{
"id": "7a7cafb91bcb055ecf36ee92e1b081ee2b058760284df898b2096720c42a6cd9",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1793090271,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: Hashing rules in C#\n\nEqual objects must have equal hash codes, so if you override Equals, override GetHashCode too. Records do both for you.\nDon't read a missing key with dict[key]: it throws KeyNotFoundException. Use TryGetValue.\nLookups are O(1) on average, but O(n) in the worst case, when many keys collide.\n\n```csharp\nvar ages = new Dictionary\u003cstring, int\u003e { [\"ann\"] = 30 };\nConsole.WriteLine(ages.TryGetValue(\"bob\", out int age) ? age : -1);\nvar set = new HashSet\u003cPoint\u003e { new Point(1, 2) };\nConsole.WriteLine(set.Contains(new Point(1, 2)));\n```\n\nIt prints -1 (no bob), then True (records compare by value).\n\nRead more: https://www.geeksforgeeks.org/dsa/hashing-data-structure/\n\n#tip · TIP-065",
"sig": "7a18e9a2f5fbf021aea07111fec02e5c2522daca753f8e43fb9d65a76f2309217684d175090303d827671db1d096e4f0cd165ffea86c23b96ed8f5e4617d573d"
}