Dictionary<TKey, TValue> · C#

Add / TryAdd

Inserts a new key; Add throws if the key exists, TryAdd returns false instead.

public void Add(TKey key, TValue value); public bool TryAdd(TKey key, TValue value)

Complexity

ExpectedO(1)
AmortizedO(1) including resizes
Worst caseO(n) when many keys collide, or during a resize
Extra spaceO(1) amortized

Assumes: Hash codes spread keys evenly over the buckets.

Hash the key, pick a bucket, walk its chain to check for a duplicate, then link a new entry. With a good hash the chains stay short; a resize rehashes all n entries but happens rarely enough to be amortized O(1).

Tested example

var ages = new Dictionary<string, int>();
ages.Add("ada", 36);
Assert.Throws<ArgumentException>(() => ages.Add("ada", 37)); // duplicate key
Assert.True(ages.TryAdd("bob", 25));
Assert.False(ages.TryAdd("bob", 26));                     // no exception, no change
Assert.Equal(25, ages["bob"]);
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
Must not be null.
value
Any value.

Behaviour

Returns
TryAdd: true if inserted.
Errors and preconditions
Add: ArgumentException for a duplicate key. Both: ArgumentNullException for a null key.
Changes
One new entry; may resize and rehash.
Memory and invalidation
Resizing allocates new buckets and entries arrays. Invalidates enumerators.