C# · Hash map · container

Dictionary<TKey, TValue>

A hash table from unique keys to values with expected O(1) insert, lookup and removal.

using System.Collections.Generic;
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue> where TKey : notnull

.NET 10 (TryAdd and Remove(key, out value) since .NET Core 2.0)

Operations

OperationTimeWorst caseChanges the collection
Add / TryAddO(1) including resizesO(n) when many keys collide, or during a resizeYes
Indexer this[TKey]O(1)O(n)Yes
TryGetValueO(1)O(n)No
ContainsKey / ContainsValueO(1) for ContainsKeyO(n) for ContainsValue (always)No
RemoveO(1)O(n)Yes

"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.

How it works

Representation
Separate chaining implemented with two arrays: buckets (indices into entries) and entries (hash code, next index, key, value). The table size is a prime and grows when entries is full.
Ordering
Unspecified. Enumeration often follows insertion order while nothing has been removed, but that is an implementation detail: never rely on it.
Duplicates
Keys are unique; values may repeat.
Mutability
Mutable. Adding during enumeration throws InvalidOperationException; since .NET Core 3.0, Remove and Clear during enumeration are allowed.
Memory and ownership
One entry per pair plus the bucket array. Capacity grows (roughly doubling to the next prime); it does not shrink unless you call TrimExcess.
Equality and comparison
Keys are compared with the IEqualityComparer<TKey> passed to the constructor, or EqualityComparer<TKey>.Default. GetHashCode and Equals must agree, and a key must not change while it is in the dictionary.

Pitfalls

  • dict[key] on a missing key throws KeyNotFoundException; use TryGetValue.
  • Add throws on a duplicate key; the indexer setter overwrites; TryAdd does neither.
  • A mutable key whose hash changes after insertion becomes unfindable.
  • Null keys are not allowed (ArgumentNullException).

Alternatives

  • SortedDictionary<TKey, TValue> for ordered keys (red-black tree, O(log n))
  • SortedList<TKey, TValue> for small, mostly read ordered maps
  • FrozenDictionary<TKey, TValue> for read-only lookups (.NET 8+)
  • ConcurrentDictionary<TKey, TValue> for multi-threaded writes

In other languages

References