C# and .NET • Modern C# baseline
Dictionaries, Sets, and Equality
Use hash-based collections with stable equality and hashing behavior.
Dictionary<TKey,TValue> maps keys to values, while HashSet<T> records unique membership. Both use equality and hash codes; keys should not change in ways that affect these after insertion. For custom key types, implement equality consistently or use an explicit comparer.
Key points
- Average lookup is fast, but hash collisions are possible.
- Never mutate equality-relevant key state while it is stored in a hash collection.
Example
var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
string word = "CSharp";
counts[word] = counts.GetValueOrDefault(word) + 1;
Console.WriteLine(counts["csharp"]);
What to expect
1
Practice exercise
Count words in a case-insensitive sentence and test how punctuation and whitespace should be handled.
Key idea: Equality and hashing are part of the collection’s correctness contract.