Dictionary<TKey, TValue> · C#

Remove

Removes a key if present; never throws for a missing key.

public bool Remove(TKey key); public bool Remove(TKey key, out TValue value)

Complexity

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

Assumes: Good hash distribution.

Find the entry in its bucket chain and unlink it. Capacity is kept.

Tested example

var ages = new Dictionary<string, int> { ["ada"] = 36, ["bob"] = 25 };
Assert.True(ages.Remove("bob"));
Assert.False(ages.Remove("bob"));                    // already gone: false, no exception
Assert.True(ages.Remove("ada", out int removed));
Assert.Equal(36, removed);
Assert.Empty(ages);
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 remove.

Behaviour

Returns
Whether a pair was removed (and its value, in the second overload).
Errors and preconditions
ArgumentNullException for a null key.
Changes
Unlinks the entry and puts its slot on a free list for reuse.
Memory and invalidation
Does not shrink. Allowed during enumeration since .NET Core 3.0.