C# – Check if key exists in dictionary

When you want to check if a key exists, use Dictionary.ContainsKey(). This returns true if the key exists and otherwise returns false. Here’s an example:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    ["Bob"] = 1,
    ["Teddy"] = 2
};


if (dictionary.ContainsKey("Bob"))
{
    Console.WriteLine("'Bob' key exists");
}
else
{
    Console.WriteLine("'Bob' key doesn't exist");
}
Code language: C# (cs)

This initializes the dictionary with a few items and then checks if one of the key exists. This outputs:

'Bob' key existsCode language: plaintext (plaintext)

Usually you’ll want to do something based on if the key exists or not, such as getting the existing value or adding a new item (if the key doesn’t exist). There are specialized methods you can use in these scenarios, which I’ll explain below.

Note: Dictionary string keys are case sensitive. Use a case insensitive dictionary if necessary.

Get value for existing key with TryGetValue()

When you want to get the value for a key, you have to first check if the key exists, otherwise you’ll run into a KeyNotFoundException. The simplest way to do this is by using Dictionary.TryGetValue(). This returns true if the key exists and outputs the value via an out parameter. Here’s an example:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    ["Bob"] = 1,
    ["Teddy"] = 2
};


if(dictionary.TryGetValue("Bob", out int val))
{
    Console.WriteLine($"Bob={val}");
}
else
{
    Console.WriteLine("'Bob' key doesn't exist");
}
Code language: C# (cs)

Because the ‘Bob’ key exists, TryGetValue() returns true and sets the out parameter to its value. This example outputs the following:

Bob=1Code language: plaintext (plaintext)

Add item if key doesn’t exist with TryAdd()

When you add an item to the dictionary, you have to check if the key exists first, otherwise you’ll get a ‘key has already been added’ exception. The simplest way to do this is by using Dictionary.TryAdd(), which adds the item only if the key doesn’t exist. Here’s an example:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    ["Bob"] = 1
};

dictionary.TryAdd("Teddy", 2);
dictionary.TryAdd("Linda", 3);
Code language: C# (cs)

TryAdd() returns false if it was unable to add the new item, indicating that the key already exists. You can check the return value, but in my experience this is rarely necessary. Here’s an example of checking TryAdd()’s return value:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    ["Bob"] = 1
};

if (!dictionary.TryAdd("Bob", 2))
{
    Console.WriteLine("Failed to add new item. 'Bob' key already exists");
}
Code language: C# (cs)

Leave a Comment