Join Nostr
2026-10-27 08:37:51 UTC

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