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
| Expected | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(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
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).