Dictionary<TKey, TValue> · C#

Indexer this[TKey]

Get returns the value for a key (throws if missing); set adds or replaces.

public TValue this[TKey key] { get; set; }

Complexity

ExpectedO(1)
Worst caseO(n)
Extra spaceO(1)

Assumes: Good hash distribution.

One hash computation and a short chain walk.

Tested example

var ages = new Dictionary<string, int> { ["ada"] = 36 };
ages["ada"] = 37;                // set: replaces
ages["cy"] = 41;                 // set: adds
Assert.Equal(37, ages["ada"]);
Assert.Throws<KeyNotFoundException>(() => ages["nobody"]); // get on a missing key throws
Runs in the test suite on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples.Tests/Collections/DictionaryExamples.cs

Parameters

key
Must not be null.

Behaviour

Returns
The value (get).
Errors and preconditions
Get: KeyNotFoundException for a missing key. Both: ArgumentNullException for a null key.
Changes
Set adds or overwrites one entry.
Memory and invalidation
Set may resize (like Add).