Check If The Key Exists In The C# Dictionary

Check If The Key Exists In The Dictionary Banner Image

Introduction

Checking the C# dictionary if the key exists is an essential tool because it guards against exceptions if you try to access the dictionary and the key does not exist. I will go into the different ways you can see if the key is already there and then take the appropriate action. Generally, if the key already exists then it is safe to access that value from the dictionary but if the key doesn't then you'll want to add a key and value to the dictionary or not do any operation.

Video Code Walkthrough

Summary Table

Overall RankMethodSpeed
1TryGetValue With Get Operation7978ms
2ContainsKey With Get Operation8389ms
3TryAdd With Add Operation9257ms
4ContainsKey With Add Operation9433ms

ContainsKey Method

ContainsKey Method Chart

The first go-to method of checking the existents of the key is the ContainsKey method. You pass into a key you want to check and it returns a bool value of true or false if the key exists in the dictionary. It is very fast and very readable so this is an excellent method to check keys.

ContainsKey Method Example Code

TryGetValue Method Syntax Image

This example shows a dictionary with the year as the key and the salary per year as the value. Before each operation, I use the ContainsKey method to check if the key exists. In the first operations set, if the key exists then does an update and prints the value from the dictionary

In the second set, after checking if the key does not exist then add the key-value pair to the dictionary and then print those values to the console.

Dictionary<int, int> salaryDictionary = new Dictionary<int, int>();//Create dictionary
salaryDictionary.Add(2000, 48000);//Add key value pair to dictionary
salaryDictionary.Add(2001, 52000);//Add key value pair to dictionary
salaryDictionary.Add(2002, 55000);//Add key value pair to dictionary
salaryDictionary.Add(2003, 59000);//Add key value pair to dictionary
salaryDictionary.Add(2004, 64000);//Add key value pair to dictionary

if (salaryDictionary.ContainsKey(2003))//Check if key is in the dictionary
{
    salaryDictionary[2003] = 5900;//Update value
    Console.WriteLine("2003 salary:" + salaryDictionary[2003]);//Access dictionary with the key to get value
}

if(!salaryDictionary.ContainsKey(2005))//Check if key is in the dictionary
{
    salaryDictionary.Add(2005, 68000);//Add key value pair to dictionary
    Console.WriteLine("2005 salary:" + salaryDictionary[2005]);//Access dictionary with the key to get value
}
Code Output
2003 salary:5900
2005 salary:68000

As expected the printed values for the updated and added key-value pairs.

TryGetValue Method

TryGetValue Method Chart

TryGetValue is another way that we can check if the key exists. It does two things at the same time. It checks if the key exists then if the key exists it returns true and the value is pushed on the out parameter. If the key does not exist then it returns false and pushes null on the out parameters. I tend to use this more than ContainsKey because usually, we don't just want to check if the key exists in the dictionary only but we want to do other operations such uses the value in the dictionary. Let's look at an example.

TryGetValue Method Code Example

TryGetValue Method Syntax Image

In this example code, TryGetValue does the key check and if true returns the salary. I then use the salary to add 5k to it and assign it to the dictionary.

The other use case is if the TryGetValue returns false if the key exists then we can use this to add a key-value pair. Let's look at the example below.

Dictionary<int, int> salaryDictionary = new Dictionary<int, int>();//Create dictionary
salaryDictionary.Add(1995, 31000);//Add key value pair to dictionary
salaryDictionary.Add(1996, 37000);//Add key value pair to dictionary
salaryDictionary.Add(1997, 41000);//Add key value pair to dictionary
salaryDictionary.Add(1998, 46000);//Add key value pair to dictionary

if (salaryDictionary.TryGetValue(1996, out int salary))//Check if the key is in the dictionary, if true return the value, else return null
{
    salaryDictionary[1996] = 5000 + salary;//Update value and add 5000 to the current salary
    Console.WriteLine("1996 salary:" + salaryDictionary[1996]);//Access dictionary with the key to get value
}

if(!salaryDictionary.TryGetValue(1999, out int salary2))
{
    salaryDictionary.Add(1999, 52000);//Add key value pair to dictionary
    Console.WriteLine("1999 salary:" + salaryDictionary[1999]);//Access dictionary with the key to get value
}

Code Output
1996 salary:42000
1999 salary:52000

We see that the first salary item has 5k correctly added.

TryAdd Method

TryAdd Method Chart

This method checks if the key exists then if it does then it will return false, but if the key does not exist then it will add the given key-value pair.

TryAdd Method Code Example

TryGetValue Method Syntax Image

In the first set, if the key does exist then it will not add a key-value pair so we can access the dictionary with that key.

In the second set, if the key does not exist then it adds the key-value pair and we can then access it by printing out the value.

Dictionary<int, int> salaryDictionary = new Dictionary<int, int>();//Create dictionary
salaryDictionary.Add(1995, 31000);//Add key value pair to dictionary
salaryDictionary.Add(1996, 37000);//Add key value pair to dictionary
salaryDictionary.Add(1997, 41000);//Add key value pair to dictionary
salaryDictionary.Add(1998, 46000);//Add key value pair to dictionary

if (!salaryDictionary.TryAdd(1996, -1))//If it can add key-value pair then the key does not exist
{
    salaryDictionary[1996] = 5000 + salaryDictionary[1996];//Update value and add 5000 to the current salary
    Console.WriteLine("1996 salary:" + salaryDictionary[1996]);//Access dictionary with the key to get value
}

if (salaryDictionary.TryAdd(1999, 52000))//If it can add key value pair then key does not exists
{
    Console.WriteLine("1999 salary:" + salaryDictionary[1999]);//Access dictionary with the key to get value
}
Code Output
1996 salary:42000
1999 salary:52000
C# Programming for Unity Game Development Specialization

COURSERA

C# Programming for Unity Game Development Specialization

4.7 (2,230 reviews)

Beginner level

No previous experience is necessary

3-months at 10 hours a week (At your pace)

$59 / month or audit, and financial aid available

If you want to learn more about C# then check out this course on Coursera. It's a 3 month course to take you through the basics of C#.

You can get started with programming using C# and apply it to Unity games in this beginner-level program. Facilitated by the University of Colorado, the program offers a chance to grasp the basics of C# and utilize the knowledge to develop Unity games.

[Full Disclosure: As an affiliate, I receive compensation if you purchase through this link]

Start Your 7-day Free Trial

Performance Test

This will be a test where 10 tests are run where each test will have 10 loops. In each loop, will be a test method run that has 5 million items in a dictionary.

ContainsKey Speed Get Operation Test Code

void TestMethod(Dictionary<string, DateTime> sourceDictionary, Dictionary<string, DateTime> destinationDictionary)
{
    if (destinationDictionary.ContainsKey(keyToCheck))
    {
        DateTime currentValue = destinationDictionary[keyToCheck].AddHours(1)   ;
    }
}

TryGetValue Speed Get Operation Test Code

void TestMethod(Dictionary<string, DateTime> sourceDictionary, Dictionary<string, DateTime> destinationDictionary)
{
    if (destinationDictionary.TryGetValue(keyToCheck, out DateTime value))
    {
        DateTime currentValue = value.AddHours(1)   ;
    }
}

ContainsKey Speed Get Operation Test Code Output

Test 1: In 0m 8s 408ms
Test 2: In 0m 8s 698ms
Test 3: In 0m 8s 438ms
Test 4: In 0m 8s 670ms
Test 5: In 0m 8s 575ms
Test 6: In 0m 8s 357ms
Test 7: In 0m 8s 375ms
Test 8: In 0m 8s 179ms
Test 9: In 0m 8s 116ms
Test 10: In 0m 8s 72ms
ContainsKey Get Average Speed:8389ms, In 10 Tests

TryGetValue Speed Get Operation Test Code Output

Test 1: In 0m 8s 256ms
Test 2: In 0m 8s 201ms
Test 3: In 0m 8s 194ms
Test 4: In 0m 8s 441ms
Test 5: In 0m 7s 985ms
Test 6: In 0m 7s 697ms
Test 7: In 0m 7s 627ms
Test 8: In 0m 7s 757ms
Test 9: In 0m 7s 803ms
Test 10: In 0m 7s 811ms
TryGetValue Get Average Speed:7978ms, In 10 Tests

ContainsKey Speed Add Operation Test Code

void TestMethod(Dictionary<string, DateTime> sourceDictionary, Dictionary<string, DateTime> destinationDictionary)
{
    foreach (KeyValuePair<string,DateTime> sourceKeyValue in sourceDictionary)
    {
        if (!destinationDictionary.ContainsKey(sourceKeyValue.Key))
        {
            destinationDictionary.Add(sourceKeyValue.Key, sourceKeyValue.Value);
        }
    }
}

TryAdd Speed Get Test Code

void TestMethod(Dictionary<string, DateTime> sourceDictionary, Dictionary<string, DateTime> destinationDictionary)
{
    foreach (KeyValuePair<string, DateTime> sourceEntry in sourceDictionary)//loop through each source dictionary entries
    {
        if(destinationDictionary.TryGetValue(sourceEntry.Key, out DateTime value))
        {
            DateTime newValue = value.AddHours(1);
        }
        else
        {
            destinationDictionary.Add(sourceEntry.Key, sourceEntry.Value);//Add key value pair to dictionary
        }
    }
}

ContainsKey Speed Test Code Output

Test 1: In 0m 9s 915ms
Test 2: In 0m 9s 450ms
Test 3: In 0m 9s 313ms
Test 4: In 0m 9s 478ms
Test 5: In 0m 9s 377ms
Test 6: In 0m 9s 337ms
Test 7: In 0m 9s 377ms
Test 8: In 0m 9s 308ms
Test 9: In 0m 9s 462ms
Test 10: In 0m 9s 306ms
ContainsKey Add Average Speed:9433ms, In 10 Tests

TryGetValue Speed Test Code Output

Test 1: In 0m 9s 343ms
Test 2: In 0m 9s 24ms
Test 3: In 0m 9s 246ms
Test 4: In 0m 9s 508ms
Test 5: In 0m 9s 287ms
Test 6: In 0m 9s 153ms
Test 7: In 0m 9s 789ms
Test 8: In 0m 8s 830ms
Test 9: In 0m 9s 104ms
Test 10: In 0m 9s 283ms
TryAdd Add Average Speed:9257ms, In 10 Tests

Conclusion

The best method suited for checking if the key exists in the dictionary is the TryGetValue Method. It does two things at time which is helpful in most cases. It checks if the keys exists and if it does then returns the value of that key which most often the case what we're trying to do.

ContainsKey is very useful because it does exactly what it says but often we do want to check the dictionary so that we can use some values there which would make TryGetValue a better option. But if you're just starting and you want your code to be readable and simple this is a good way of going.

The best method suited for checking if the key exists in the dictionary is the TryGetValue Method. It does two things at a time which is helpful in most cases. It checks if the keys exist and if it does then returns the value of that key which is most often the case of what we're trying to do.

TryAdd does the ContainsKey checks as well but just checking if the key exists, makes this option not easy to use and it would be better to use it if you're trying to add values only.

Know any other ways to check if the key exists in a dictionary? Let me know in the comments.

Get Latest Updates