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

ExpectedO(1)
Worst caseO(n)
Extra spaceO(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"));
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
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.