Dictionary<TKey, TValue> · C#
TryGetValue
Looks a key up once and reports whether it was found, without exceptions.
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
Complexity
| Expected | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(1) |
Assumes: Good hash distribution.
One lookup. ContainsKey followed by the indexer does the same work twice.
Tested example
var ages = new Dictionary<string, int> { ["ada"] = 36 };
if (ages.TryGetValue("ada", out int age))
Assert.Equal(36, age);
Assert.False(ages.TryGetValue("nobody", out _)); // one lookup, no exception
Assert.Equal(0, ages.GetValueOrDefault("nobody"));
Parameters
- key
- The key to find.
Behaviour
- Returns
- true and the value if found; false and default(TValue) otherwise.
- Errors and preconditions
- ArgumentNullException for a null key.
- Changes
- Nothing.
- Memory and invalidation
- No allocation.