Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 182 ยท Collections

Dictionary of TKey, TValue

Learn the C# Dictionary<TKey, TValue> - adding, indexer, TryGetValue, GetValueOrDefault, TryAdd, iteration, key equality and GetHashCode, custom comparers and ordering.

A list finds things by position: "give me item 7". But often you know a name, not a position: the price of "espresso", the user with id 4021, the number of times the word "the" appears. A dictionary stores key/value pairs and finds a value by its key almost instantly, no matter how many entries there are. In C# the type is Dictionary<TKey, TValue>, for example Dictionary<string, decimal> for prices.

Dictionaries are one of the most useful tools in programming: caches, lookup tables, counting, grouping and indexes are all dictionaries. This lesson covers the safe ways to read and write entries, how to loop over a dictionary, how keys are compared (and what GetHashCode has to do with it), custom comparers for case-insensitive keys, a fast counting idiom, and why you must never rely on the order of entries.

Creating a dictionary and adding entries

C# Creating and reading a dictionary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The indexer dict[key] = value is the everyday way to set a value: it adds a new entry or overwrites an existing one. Add is stricter and treats a duplicate key as a bug. ContainsKey checks keys quickly; ContainsValue has to scan every entry, so it is O(n).

The two ways reading can fail

Reading with the indexer for a key that does not exist throws, and adding a duplicate throws:

C# KeyNotFoundException and duplicate keys (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The Add failure is caught and printed (An item with the same key has already been added. Key: apple). The last line is not caught and ends the program with System.Collections.Generic.KeyNotFoundException: The given key 'pear' was not present in the dictionary.

TryGetValue and GetValueOrDefault

If a key might be missing, do not use ContainsKey followed by the indexer: that looks the key up twice. TryGetValue does a single lookup, returns whether it found the key, and delivers the value through an out variable:

C# Safe lookups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that GetValueOrDefault cannot tell "missing" from "present with the default value": "pear" and "plum" both give 0. When the difference matters, use TryGetValue. TryAdd is the non-throwing Add, and Remove returns false if the key was not there.

Looping over a dictionary

Each entry is a KeyValuePair<TKey, TValue> with Key and Value properties. You can deconstruct it directly in a foreach. You can also loop over just Keys or Values.

C# Iterating entries, keys and values (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

We sort the entries before printing for a reason, which the next section explains. The last loop throws System.InvalidOperationException: Collection was modified; enumeration operation may not execute. Adding or removing entries during enumeration is always an error. (Overwriting the value of an existing key happens to be allowed in modern .NET, but do not rely on that.) To change a dictionary while visiting it, loop over a copy of the keys: foreach (var key in capitals.Keys.ToList()).

Never rely on dictionary order. In practice a Dictionary<int, T> that never had entries removed often enumerates in insertion order, which tempts people to depend on it. But the order is an implementation detail, it changes after removals, and for string keys the order can differ from one run of the program to the next because string hash codes are randomized per process. If you need sorted output, sort when you print, or use SortedDictionary (Sorted collections).

How keys are compared: Equals and GetHashCode

A dictionary is a hash table. To store a key, it calls GetHashCode() to get a number, uses that number to choose a bucket, and then uses Equals to compare the new key with the keys already in that bucket. This is why lookups are O(1) on average: instead of searching everything, it jumps to the right bucket.

This has an important consequence for your own key types. Two objects that are equal must return the same hash code. For built-in types like int, string, Guid, enums, tuples and records this is already done correctly. A plain class uses reference equality by default:

C# Keys: class vs record vs tuple

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The class key is not found because the second new PointClass(1, 2) is a different object with a different hash. Records and tuples work out of the box. For a class (or struct) you must override both Equals and GetHashCode together, as Money does; HashCode.Combine is the easy way to build the hash.

Keys must be immutable (at least the parts used by Equals and GetHashCode). If you change a key object after storing it, its hash code changes and the dictionary can no longer find the entry. It is still there, taking up space, but unreachable.

Custom comparers: case-insensitive keys

The constructor accepts an IEqualityComparer<TKey> to change how keys are compared. The classic use is case-insensitive string keys:

C# StringComparer.OrdinalIgnoreCase

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Pick the comparer when you create the dictionary; you cannot change it afterwards. StringComparer.Ordinal (the default for strings) compares raw characters, which is both fast and culture-independent. Use OrdinalIgnoreCase for identifiers, file names, HTTP headers and similar; avoid culture-sensitive comparers for keys.

Counting and grouping

Dictionaries are the natural tool for counting. The straightforward version looks the key up twice:

C# Word frequency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The second half shows the "get or create the list" pattern, used for grouping. For high-performance counting there is an advanced helper that performs a single lookup and gives you a reference to the stored value:

C# CollectionsMarshal.GetValueRefOrAddDefault

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

GetValueRefOrAddDefault finds the entry (adding one with default(int) if needed) and returns a ref to the value stored in the table, so slot++ updates it in place with only one hash lookup. Do not add or remove entries while you hold the ref, because the table may be resized. Use it only in hot code; the simple version is clearer.

Performance notes

  • Add, TryGetValue, indexer and Remove are O(1) on average. Worst case is O(n) with many hash collisions, which good GetHashCode implementations avoid.
  • A dictionary uses more memory than a list of the same data. For tiny collections (a few entries), a list with a linear search can be faster.
  • Pass an expected size to the constructor (new Dictionary<int, string>(10_000)) to avoid repeated resizing.
  • For read-mostly lookup tables created once, FrozenDictionary gives faster reads (Immutable and frozen collections).
  • Dictionary<TKey, TValue> is not thread-safe for concurrent writes; use ConcurrentDictionary or a lock.

Common mistakes

  • Using the indexer to read a key that may be missing. Use TryGetValue.
  • Calling ContainsKey and then the indexer: two lookups for one answer.
  • Mutable keys or a class key without Equals/GetHashCode.
  • Assuming order. Sort when you print.
  • Adding or removing entries inside foreach.
  • Using null as a key: Dictionary throws ArgumentNullException.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between dict.Add(key, value) and dict[key] = value when the key already exists?

    Add treats a duplicate as an error and throws ArgumentException. The indexer assigns, adding a new entry or replacing the existing value.
  2. 2. Which is the best way to read a value that might not be in the dictionary?

    TryGetValue does a single lookup and tells you whether the key existed, without throwing.
  3. 3. Why does a Dictionary<PointClass, string> fail to find new PointClass(1, 2) when a different PointClass(1, 2) object was stored, and the class overrides nothing?

    Without overriding Equals and GetHashCode, two separate objects are different keys. Records, tuples and classes with correct overrides compare by content.
  4. 4. How do you create a dictionary whose string keys ignore letter case?

    The constructor accepts an IEqualityComparer. StringComparer.OrdinalIgnoreCase treats "Theme" and "theme" as the same key.
  5. 5. What can you rely on about the order of entries when you enumerate a Dictionary?

    The order is an implementation detail that changes with removals and, for string keys, can vary between runs. Sort when you need an order.

Summary

  • Dictionary<TKey, TValue> maps unique keys to values with O(1) average lookup, insert and remove.
  • dict[key] = value adds or replaces; Add throws on duplicates; TryAdd returns a bool.
  • Use TryGetValue (one lookup) or GetValueOrDefault for keys that may be missing; the indexer throws KeyNotFoundException.
  • Keys are compared with GetHashCode and Equals; use immutable keys, records, tuples or classes that override both.
  • Pass a comparer such as StringComparer.OrdinalIgnoreCase to change key equality.
  • Never rely on enumeration order; sort explicitly, and do not modify the dictionary while looping over it.

Next: HashSet, SortedSet and Set Operations