C# – Add to a dictionary

The simplest way to add a key/value pair to a dictionary is by using Dictionary.Add(), like this:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>();

dictionary.Add("Bob", 1);
Code language: C# (cs)

If the key already exists, Dictionary.Add() throws an ArgumentException because the key must be unique.

There are a few other ways to add to a dictionary in different scenarios, which I’ll explain below.

Add or update key/value in dictionary

You can use the dictionary indexer syntax to add a new key/value pair -or- overwrite the value if the key already exists (instead of throwing an exception). Here’s an example:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>();

dictionary["Bob"] = 1;
dictionary["Bob"] = 100;
Code language: C# (cs)

This is a simple way to add/overwrite without having to explicitly check if the key exists yourself.

Initialize key/value or increment the value

Let’s say you want to initialize a key’s value to some value (such as 0) and want to increment it by 1 if the key already exists. To do this, you have to explicitly check if the key exists and set the initial value. In this situation, you can use Dictionary.TryGetValue() to get the current value. If this returns true, you can update the value. If it returns false, you can set the initial value. Here’s an example:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>();

string key = "Bob";

if (dictionary.TryGetValue(key, out int currentValue))
{
    dictionary[key] = currentValue + 1;
}
else
{
    dictionary[key] = 0; //set initial value
}
Code language: C# (cs)

You have to check if the key exists first because only using the indexer syntax (i.e. dictionary[key]++) results in a KeyNotFoundException. This is because it has to lookup the existing value in order to increment it and the key doesn’t exist yet, hence the exception.

Add to the dictionary if the key doesn’t exist

You can use Dictionary.TryAdd() to attempt to add a key/value pair to the dictionary. If the key already exists, it returns false instead of throwing an exception. Here’s an example:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>();

dictionary.TryAdd("Bob", 1);
dictionary.TryAdd("Bob", 2);

Console.WriteLine($"Bob={dictionary["Bob"]}");
Code language: C# (cs)

This outputs the following (notice that it didn’t overwrite the value and didn’t throw an exception):

Bob=1Code language: plaintext (plaintext)

This is a shortcut for using Dictionary.ContainsKey() and Dictionary.Add().

If necessary, you can check the output of TryAdd(). It returns true if it added the key/value pair. Here’s an example:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>();

if (dictionary.TryAdd("Bob", 1))
{
    Console.WriteLine("Added key/value pair!");
}
Code language: C# (cs)

Add multiple items when creating the dictionary

Another way to add key/value pairs to a dictionary is by using the collection initializer syntax. This allows you add items as you’re creating the dictionary. This is equivalent to using the indexer syntax repeatedly, it’s just more concise. Here’s an example:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    ["Bob"] = 1,
    ["Linda"] = 2,
    ["Teddy"] = 3
};
Code language: C# (cs)

Note: If you have a list of items to add, you can convert the list to a dictionary with ToDictionary().

Leave a Comment