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.

ContainsKey Method

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

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

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

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

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

Conclusion

Overall RankMethod
1TryGetValue
2ContainsKey
3TryAdd

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
Comments Section