C# Dictionary TryAdd() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Dictionary

Definition

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
CallWhat 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

ParameterDescription
keyRequired. The key to add. It must not be null.
valueRequired. The value to store if the key is new.

Return Value

Return ValueDescription
booltrue 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);
    }
}

How It Works

  1. First call. The key "Asha" is new, so the pair is stored and the call returns True.
  2. Second call. The key is now taken, so nothing is stored and the call returns False. No exception is thrown.
  3. Old value stays. ages["Asha"] is still 25, not 99.
  4. 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"]);
    }
}

How It Works

  1. Index as value. The loop passes i as the value, so each word is linked to a position.
  2. Repeats counted. !TryAdd(...) is true only when the key already exists, so repeats rises for the second "red" and the second "blue".
  3. Three unique words. Five words went in, two were repeats, so Count is 3.
  4. 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");
        }
    }
}

How It Works

  1. Indexer overwrites. ages["Asha"] = 30 replaces 25 with 30, so the first line prints 30.
  2. TryAdd refuses. The key exists, so TryAdd returns False and the value stays 30, not 40.
  3. Add throws. The same duplicate key makes Add throw ArgumentException, which the catch block turns into a message.
  4. 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.

Next: TryGetValue()

Read a value by key safely, with one lookup and no exception if the key is missing.

TryGetValue() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful