Dictionary<TKey, TValue> · C#

ContainsKey / ContainsValue

ContainsKey hashes the key; ContainsValue has no index and scans every entry.

public bool ContainsKey(TKey key); public bool ContainsValue(TValue value)

Complexity

ExpectedO(1) for ContainsKey
Worst caseO(n) for ContainsValue (always)
Extra spaceO(1)

Keys are hashed into buckets; values are not indexed at all, so finding one means visiting every entry.

Tested example

var ages = new Dictionary<string, int> { ["ada"] = 36 };
Assert.True(ages.ContainsKey("ada"));
Assert.False(ages.ContainsValue(99)); // ContainsValue scans every entry: O(n)
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 / value
What to look for.

Behaviour

Returns
Whether it is present.
Errors and preconditions
ContainsKey: ArgumentNullException for a null key.
Changes
Nothing.
Memory and invalidation
No allocation.