In C#, Dictionary.TryAdd(key, value) tries to add a new pair. If the key is new, it adds the pair and returns true. If the key is already there, it changes nothing and returns false.
That makes it the calm cousin of Add(): you get a yes or no answer instead of an exception, and you do only one lookup instead of ContainsKey plus Add.
This is an instance member of Dictionary<TKey,TValue> (System.Collections.Generic). Call it on a dictionary variable, such as ages.TryAdd(...). A dictionary is a class, so two variables can share one dictionary. TryAdd exists in .NET Core 2.0 and later, .NET Standard 2.1, and .NET 5 and later. It is not in .NET Framework.
Syntax
Call TryAdd and use the bool result if you care whether the key was new.
C#
Dictionary<string, int> ages = new Dictionary<string, int>();
bool first = ages.TryAdd("Asha", 25); // true: added
bool second = ages.TryAdd("Asha", 99); // false: key exists, value stays 25
Call
What it does
ages.TryAdd("Asha", 25)
Adds the pair and returns true when "Asha" is new.
ages.TryAdd("Asha", 99)
Returns false and keeps the old value when "Asha" already exists.
if (!ages.TryAdd(k, v)) { ... }
Run code only for repeats, such as logging a duplicate.
A null key still throws ArgumentNullException. TryAdd never overwrites; if you want to overwrite, use the indexer.
Library declarations
C#
public bool TryAdd(TKey key, TValue value);
Parameters
Parameter
Description
key
Required. The key to add. It must not be null.
value
Required. The value to store if the key is new.
Return Value
Return Value
Description
bool
true if the pair was added; false if the key was already in the dictionary.
C# Examples
Example 1 — Add the Same Key Twice
Call TryAdd two times with the same key and watch the results.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, int> ages = new Dictionary<string, int>();
Console.WriteLine(ages.TryAdd("Asha", 25));
Console.WriteLine(ages.TryAdd("Asha", 99));
Console.WriteLine(ages["Asha"]);
Console.WriteLine(ages.Count);
}
}
Output
True
False
25
1
How It Works
First call. The key "Asha" is new, so the pair is stored and the call returns True.
Second call. The key is now taken, so nothing is stored and the call returns False. No exception is thrown.
Old value stays.ages["Asha"] is still 25, not 99.
Still one pair.Count is 1 because the second call did not add anything.
Example 2 — Remember Where Each Word First Appears
Store the first index of every word. Repeats are ignored because TryAdd keeps the first value.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
string[] words = { "red", "blue", "red", "green", "blue" };
Dictionary<string, int> firstSeen = new Dictionary<string, int>();
int repeats = 0;
for (int i = 0; i < words.Length; i++) {
if (!firstSeen.TryAdd(words[i], i)) {
repeats++;
}
}
Console.WriteLine(firstSeen.Count);
Console.WriteLine(repeats);
Console.WriteLine(firstSeen["red"]);
Console.WriteLine(firstSeen["green"]);
}
}
Output
3
2
0
3
How It Works
Index as value. The loop passes i as the value, so each word is linked to a position.
Repeats counted.!TryAdd(...) is true only when the key already exists, so repeats rises for the second "red" and the second "blue".
Three unique words. Five words went in, two were repeats, so Count is 3.
First index kept."red" maps to 0, not 2, and "green" maps to 3, because later repeats were refused.
Example 3 — Three Ways to Write an Existing Key
Start with Asha=25 and try the indexer, TryAdd, and Add on the same key.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Asha", 25);
ages["Asha"] = 30;
Console.WriteLine(ages["Asha"]);
bool added = ages.TryAdd("Asha", 40);
Console.WriteLine(added);
Console.WriteLine(ages["Asha"]);
try {
ages.Add("Asha", 50);
} catch (ArgumentException) {
Console.WriteLine("Add threw");
}
}
}
Output
30
False
30
Add threw
How It Works
Indexer overwrites.ages["Asha"] = 30 replaces 25 with 30, so the first line prints 30.
TryAdd refuses. The key exists, so TryAdd returns False and the value stays 30, not 40.
Add throws. The same duplicate key makes Add throw ArgumentException, which the catch block turns into a message.
Pick by intent. Use the indexer for "latest wins", TryAdd for "first wins", and Add when a duplicate is a bug.
Frequently Asked Questions
It returns true when the key was new and the pair was added, and false when the key already existed.
No. When the key exists, TryAdd returns false and leaves the old value alone. Use the indexer to overwrite.
TryAdd is available in .NET Core 2.0 and later, .NET Standard 2.1, and .NET 5 and later. It is not in .NET Framework, where you use ContainsKey and Add.
Usually yes. TryAdd finds the slot once, while ContainsKey followed by Add does two lookups.
Only for a null key. It never throws for a duplicate key.