Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Collections

The Dictionary<TKey,TValue> class

Reference for C# Dictionary<TKey,TValue>: adding, reading and removing entries, key rules, KeyNotFoundException, custom comparers, ordering and complexity.

Dictionary<TKey,TValue> stores key/value pairs and finds a value by its key in constant time on average. It is a hash table: the key's GetHashCode() picks a bucket and Equals() confirms the match. Keys must be unique and (for reference types) non-null; values can repeat and can be null.

Use a dictionary whenever you look things up by something other than a position: users by id, prices by product code, counts by word. For the everyday operations beyond the basics, see Dictionary operations.

C#
var ages = new Dictionary<string, int> { ["Ann"] = 31, ["Bob"] = 25 };
ages["Cy"] = 40;
Console.WriteLine(ages["Ann"]);   // 31

Try it

C# Add, read, update, remove

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.

C# Errors, comparers and custom keys

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.

Syntax

C#
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>
    where TKey : notnull
{
    public Dictionary();
    public Dictionary(int capacity);
    public Dictionary(IEqualityComparer<TKey>? comparer);
    public Dictionary(IDictionary<TKey, TValue> dictionary);

    public TValue this[TKey key] { get; set; }
    public int Count { get; }
    public Dictionary<TKey, TValue>.KeyCollection Keys { get; }
    public Dictionary<TKey, TValue>.ValueCollection Values { get; }

    public void Add(TKey key, TValue value);
    public bool Remove(TKey key);
    public bool ContainsKey(TKey key);
    public bool ContainsValue(TValue value);
    public void Clear();
}
Name Description
key The lookup key. Must not be null. Equality and hashing come from the comparer (default: EqualityComparer<TKey>.Default).
value The associated value.
capacity Expected number of entries, to avoid rehashing while filling.
comparer Custom equality, such as StringComparer.OrdinalIgnoreCase.

Returns: Remove and ContainsKey return bool. The indexer returns the value for the key. Keys and Values are live views, not copies.

Errors: the indexer getter throws KeyNotFoundException when the key is absent. Add throws ArgumentException if the key already exists. A null key throws ArgumentNullException. Adding to the dictionary while enumerating it throws InvalidOperationException.

Usage notes

  • Lookup, add and remove are O(1) on average and O(n) in the worst case when many keys collide. ContainsValue is always O(n).
  • Indexer set versus Add. dict[key] = v adds or replaces silently; Add fails on a duplicate. Choose deliberately.
  • Avoid the double lookup. if (d.ContainsKey(k)) use(d[k]) hashes twice. Use TryGetValue instead.
  • Enumeration order is unspecified. In practice entries often come back in insertion order, but removals and re-adds reuse slots. Sort or use SortedDictionary when order matters.
  • Keys must keep their hash stable. Mutating a key object after inserting it makes the entry unreachable. Prefer immutable keys: strings, numbers, records, tuples.
  • Custom key types need consistent Equals and GetHashCode. Records and tuples provide both.
  • String keys: pass StringComparer.Ordinal or OrdinalIgnoreCase explicitly for predictable, fast comparisons.
  • Memory: a dictionary is considerably bigger than a list of the same entries because of the hash buckets.
  • Not thread-safe for concurrent writes; use ConcurrentDictionary or a lock.