skip to content

Dictionaries and Sets

Dictionary<TKey,TValue> and HashSet<T> hash keys through GetHashCode and a comparer, so the comparer decides which keys count as equal. Interviewers ask about lookups, ordering and comparers.

on this pageshow

explore

questions

6

With C#'s Dictionary<TKey,TValue>, what does the indexer do for a missing key, and when do TryGetValue, TryAdd and Add fit better?

level: juniorimportance: must knowfreq 78%

answer

  1. the indexer has two halves
  2. what a missing read raises
  3. a write never complains
  4. duplicate keys and Add
  5. bool-returning Try methods

basics

~20 s

Reading a missing key through Dictionary<TKey,TValue>'s indexer throws KeyNotFoundException; writing through it adds or silently overwrites. Use TryGetValue when absence is normal, Add when a duplicate is a bug, and TryAdd to insert only if absent.

solid answer

~40 s

The indexer `dict[key]` has two contracts. The getter throws `KeyNotFoundException` when the key is absent; the setter inserts the pair if the key is new and overwrites the value if it exists, without telling you which happened. `Add(key, value)` inserts only a new key and throws `ArgumentException` on a duplicate, so use it where a duplicate means a bug. `TryAdd` inserts only if the key is absent and returns `false` instead of throwing or overwriting. `TryGetValue(key, out value)` does one lookup and returns `false` for a missing key, which is the right read whenever absence is expected; `GetValueOrDefault` is shorthand when a fallback value is enough. Catching `KeyNotFoundException` as control flow is the pattern to avoid.

code

csharp · 24 lines
csharp
var stock = new Dictionary<WarehouseBin, int>();
var a1 = new WarehouseBin("A", 1, 4);
stock[a1] = 12;          // indexer write: adds
stock[a1] = 9;           // indexer write: overwrites silently
Console.WriteLine(stock[a1]);                        // 9

Console.WriteLine(stock.TryAdd(a1, 50));             // False, value stays 9
Console.WriteLine(stock.GetValueOrDefault(new WarehouseBin("B", 2, 1)));     // 0
Console.WriteLine(stock.GetValueOrDefault(new WarehouseBin("B", 2, 1), -1)); // -1

if (stock.TryGetValue(new WarehouseBin("C", 3, 7), out int qty))
    Console.WriteLine(qty);
else
    Console.WriteLine("C-3-7 not stocked");

try { stock.Add(a1, 5); }
catch (ArgumentException ex) { Console.WriteLine($"{ex.GetType().Name}: {ex.Message}"); }

try { Console.WriteLine(stock[new WarehouseBin("C", 3, 7)]); }
catch (KeyNotFoundException ex) { Console.WriteLine($"{ex.GetType().Name}: {ex.Message}"); }

Console.WriteLine(stock.Remove(a1, out int removed) + " " + removed);  // True 9

readonly record struct WarehouseBin(string Aisle, int Shelf, int Slot);

go deeper

for a junior

Recall the asymmetry: a missing read through the indexer throws KeyNotFoundException, while a write adds or overwrites. Name TryGetValue as the normal way to read a key that may be absent.

for a middle

Explain the three insertion policies, Add throwing, the setter overwriting and TryAdd skipping, and why GetValueOrDefault cannot tell a stored default from a missing key.

for a senior

Show that you pick the call from the domain rule: a duplicate import row is a bug, a live feed is last-write-wins, a cache fill is first-write-wins, and exceptions never carry expected misses on hot paths.

for a principal

Frame it as a review convention: enable CA1854 and CA1864, and ask at each call site which insertion policy was intended, because the setter's silent overwrite is where data quietly disappears.

## The indexer has two different contracts `Dictionary<TKey,TValue>` maps each **key** to one **value** and finds the key by hashing it. Its indexer, `this[TKey key]`, looks like one member but carries two policies: - The **getter** looks the key up and returns the value. If the key is absent it throws `KeyNotFoundException`, and on .NET 10 the message includes the key's `ToString()` output, for example `The given key 'WarehouseBin { Aisle = C, Shelf = 3, Slot = 7 }' was not present in the dictionary.` - The **setter** inserts the pair when the key is new and **overwrites** the existing value when it is not. It never throws for a duplicate and never reports which of the two happened. A `null` key is rejected with `ArgumentNullException` by every member that takes a key, because the dictionary must hash the key before it can do anything else. ## Three insertion policies The type offers three ways to put a pair in, and each one encodes a different intent: | Call | Key absent | Key present | Returns | |---|---|---|---| | `dict[key] = value` | adds | overwrites, silently | nothing | | `Add(key, value)` | adds | throws `ArgumentException` | nothing | | `TryAdd(key, value)` | adds | leaves the old value | `bool` | In a warehouse service that indexes stock by a `WarehouseBin(Aisle, Shelf, Slot)` key, each maps to a real rule: 1. A nightly import where each bin must appear once uses `Add`, so a duplicated row fails loudly instead of quietly replacing the first count. 2. A live feed where the latest count wins uses the setter. 3. A cache fill where the first writer wins uses `TryAdd` and ignores the `false`. The duplicate message from `Add` names the key too: `An item with the same key has already been added. Key: WarehouseBin { Aisle = A, Shelf = 1, Slot = 4 }`. ## Reading a key that may be missing - `TryGetValue(TKey key, out TValue value)` performs **one** lookup, returns `true` with the value, or `false` with `value` set to `default`. It is the standard read when absence is an expected outcome. - `GetValueOrDefault(key)` and `GetValueOrDefault(key, defaultValue)` are extension methods on `IReadOnlyDictionary<TKey,TValue>` in `CollectionExtensions`. They are handy, but `GetValueOrDefault(bin)` on a `Dictionary<WarehouseBin, int>` returns `0` both for an unknown bin and for a bin stocked with zero. A variable typed as `IDictionary<TKey,TValue>` does not see them, because that interface does not extend `IReadOnlyDictionary<TKey,TValue>`. - `Remove(TKey key, out TValue value)` removes the entry and hands back the old value in one call, returning `false` when the key was not there. ```csharp if (stock.TryGetValue(bin, out int qty)) Console.WriteLine($"{bin}: {qty}"); else Console.WriteLine($"{bin} is not stocked"); ``` ## Why not catch the exception, or check first? Wrapping the getter in `try`/`catch (KeyNotFoundException)` turns an ordinary outcome into an exception: the runtime builds an exception object, captures a stack trace and unwinds, which costs far more than a failed lookup. It also hides real bugs, since the `catch` will swallow a `KeyNotFoundException` thrown by any code inside the `try`. `if (dict.ContainsKey(key)) return dict[key];` is correct but searches twice, once in `ContainsKey` and once in the getter. The .NET code analyzers flag it as **CA1854** (prefer `TryGetValue`), and `ContainsKey` followed by `Add` as **CA1864** (prefer `TryAdd`); both are enabled as suggestions in .NET 10. ## Reading the exceptions in a log Each failure mode of the type throws something different, which makes production logs easy to triage: | Exception | Thrown by | Meaning | |---|---|---| | `ArgumentNullException` | any member given a `null` key | the caller passed no key at all | | `ArgumentException` | `Add` with an existing key | a duplicate the code did not expect | | `KeyNotFoundException` | the indexer getter | a read of a key that was never stored or was removed | Both the duplicate and the missing-key messages print the key, so a record struct key such as `WarehouseBin` shows its aisle, shelf and slot right in the log line. A key type whose `ToString()` is the default type name gives you much less to work with, which is a small argument for keys with a readable `ToString()`. ## Habits worth keeping - Read with `TryGetValue` unless a missing key truly is a bug; then the getter's exception is the right signal. - Choose the insertion call by intent: `Add` for must-be-new, the setter for last-write-wins, `TryAdd` for first-write-wins. - Use `GetValueOrDefault` only when `default(TValue)` cannot be a legitimate stored value, or pass an explicit fallback. - Treat a `KeyNotFoundException` in production logs as a design question about whether absence was expected, not as something to catch.

  • Why is catching KeyNotFoundException worse than calling TryGetValue?
    A missing key is a normal outcome, and an exception for it costs an allocation, a stack-trace capture and unwinding, far more than a failed lookup. It also blurs intent: a `catch (KeyNotFoundException)` around a block swallows the same exception from any nested call, hiding real bugs. `TryGetValue` states that absence is expected and costs one lookup.
  • When does GetValueOrDefault mislead you?
    When `default(TValue)` is a value the dictionary can legitimately hold. On a `Dictionary<WarehouseBin, int>`, `GetValueOrDefault(bin)` returns `0` for an unknown bin and for a bin stocked with zero. Use `TryGetValue` when the difference matters, or the overload that takes an explicit fallback such as `-1`.
  • What does Remove(key, out value) give you over Remove(key)?
    It removes the entry and returns the value it held in a single lookup, returning `false` with `value` set to `default` when the key was absent. Without it you would call `TryGetValue` and then `Remove`, searching twice.

  • The indexer returns null or default when the key is missing.
  • Assigning through the indexer throws when the key already exists.
  • TryAdd overwrites the stored value when the key is already present.
  • Catching KeyNotFoundException is the normal way to handle an expected miss.
  • ContainsKey followed by the indexer costs no more than TryGetValue.
open as a page

In C#, how do you key a Dictionary<TKey,TValue> or HashSet<T> by a class you cannot modify that only has reference equality?

level: middleimportance: should knowfreq 48%

basics

~10 s

Write an IEqualityComparer<T> whose Equals and GetHashCode use the identifying fields and pass it to the Dictionary<TKey,TValue> or HashSet<T> constructor; every lookup then hashes and compares keys through it instead of reference equality.

open as a page

In C#, what do HashSet<T>'s UnionWith, IntersectWith and ExceptWith do to the set you call them on, and how do SetEquals and IsSubsetOf compare?

level: middleimportance: should knowfreq 45%

basics

~20 s

UnionWith, IntersectWith and ExceptWith mutate the HashSet<T> they are called on and return void, so copy the set first if you still need it. SetEquals and IsSubsetOf only test, ignoring order and duplicates in the other collection.

open as a page

In .NET, why must code not rely on Dictionary<TKey,TValue> enumeration order, and when does OrderedDictionary<TKey,TValue> or SortedDictionary<TKey,TValue> fit instead?

level: middleimportance: should knowfreq 38%

basics

~10 s

Dictionary<TKey,TValue> promises no enumeration order, and after a Remove the next insertion reuses the freed slot mid-sequence. OrderedDictionary<TKey,TValue> (.NET 9) keeps insertion order with index access; SortedDictionary<TKey,TValue> keeps key order.

open as a page

A hot C# loop updates a Dictionary<TKey,TValue> with ContainsKey and then the indexer — how do you cut the repeated lookups, and what makes CollectionsMarshal.GetValueRefOrAddDefault risky?

level: seniorimportance: should knowfreq 32%

basics

~20 s

ContainsKey plus the indexer hashes the key twice, three times for read-modify-write. Use TryGetValue or TryAdd for one lookup, or CollectionsMarshal.GetValueRefOrAddDefault to update in place, but never add or remove entries while holding that ref.

open as a page

In .NET, how do SortedDictionary<TKey,TValue> and SortedList<TKey,TValue> differ in structure, insertion cost, memory and index access, and when does each win?

level: seniorimportance: should knowfreq 34%

basics

~20 s

SortedDictionary<TKey,TValue> is a red-black tree: O(log n) insert and remove, one node object per entry, no index access. SortedList<TKey,TValue> is two sorted arrays: O(log n) lookup, O(n) insert or remove except at the end, less memory, index access.

open as a page