In this article, we are going to talk about the Dictionary in C#. We will learn how to create a dictionary, add, retrieve, update, and delete elements. Among that, we will see the usage of its common properties and methods.

To download the source code for this article, you can visit our GitHub repository.

Let’s begin.

What Is Dictionary in C#?

Dictionary<TKey,TValue> is a generic collection that stores the data in key-value pairs. It implements IDictionary<TKey,TValue> interface.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

In C# we don’t have a built-in Map type. But we can use Dictionary<TKey,TValue> to map objects. It is a useful tool that allows us to map value to a key.

A dictionary cannot have null or duplicate keys, whereas it can have null and duplicate values.

Now, let’s look at its implementation.

Create a Dictionary in C#

Let’s take a look at three ways to create a dictionary.

Initializing an Empty Dictionary

Let’s start by creating an empty dictionary:

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

We create the dict1 dictionary with an empty constructor, and it doesn’t have any data. We do it this way if we want to create an empty dictionary.

Initializing With the Number of Elements

Another way we can initialize a dictionary is by setting the number of elements: 

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

We can use this implementation if we want to define the initial capacity of our dictionary. If we know the number of elements we are going to store in our dictionary, it is always great for performance to define an initial capacity.

Initializing With Data

In addition, we can also populate the dictionary with some data:

var dict3 = new Dictionary<int, string>()
{
    {1, "Red"},
    {2, "Yellow"},
    {3, "Green"},
};

We have seen how to create a dictionary.

Now, let’s dive in deeper and create a Dictionary<int, Product> that maps a Product value to a key. We will use this for the rest of our application.

That said, let’s inspect our Product class:

public class Product
{
    public int ProductId { get; set; }
    public string? ProductName { get; set; }
}

We will first create an empty productsDict dictionary:

var productsDict = new Dictionary<int, Product>();

Let’s carry on and look at how to add elements, fetch, update, and delete its elements.

Add Elements to a Dictionary in C#

We can add elements to productsDict by using the built-in Add(TKey,TValue) method:

productsDict.Add(0, new Product() { ProductId = 111, ProductName = "Table" });
productsDict.Add(1, new Product() { ProductId = 112, ProductName = "Chair" });
productsDict.Add(2, new Product() { ProductId = 113, ProductName = "TV" });

After we execute the code, productsDict now has 3 <int, Product> key-value pairs as its elements.

Remember, we said a dictionary cannot have duplicate keys. Then, what happens if we add an element with a key that already exists? Yes, it will throw an exception.

So, we should always check whether the key we are trying to add is already added.

Let’s see a demonstration of facing this exception:

try
{
    productsDict.Add(2, new Product() { ProductId = 113, ProductName = "Wardrobe" });
}
catch (ArgumentException ex)
{
    Console.WriteLine(ex.Message);
}

In our productDict dictionary, we already have a key with a value of 2. Therefore, it is not possible to add a Product as a value with the same key – we will come across an exception. 

In order to handle the exception, we wrap the Add(TKey,TValue) method with a try/catch block.

After we run our app, we can inspect the error message in the console window:

An item with the same key has already been added. Key: 2

To prevent this, without needing to use try/catch blocks, we can use the TryAdd(TKey,TValue) method:

if (productsDict.TryAdd(3, new Product() { ProductId = 114, ProductName = "Lamp" }))
{
    Console.WriteLine($"Product is added.");
}

This method attempts to add the element to the dictionary. It returns true if it can successfully add the element, or it returns false and skips the if statement without raising an exception.

When we add a new key value such as 3, the method returns true and then successfully adds the new Product to productsDict.

As a result, we see the console output:

Product is added.

Retrieve Elements From a Dictionary in C#

To retrieve elements from a dictionary in C#, we iterate through the dictionary and get them as KeyValuePair objects.

Here’s how we do it with a foreach loop:

foreach (KeyValuePair<int, Product> product in productsDict)
{
    Console.WriteLine($"Key = {product.Key}, Value = {product.Value.ProductId}, {product.Value.ProductName}");
}

We iterate through each KeyValuePair in productsDict to fetch the mapped value. As a result, we obtain Product object with its ProductId and ProductName properties:

Key = 0, Value = 111, Table
Key = 1, Value = 112, Chair
Key = 2, Value = 113, TV
Key = 3, Value = 114, Lamp

There are also other ways to iterate through a dictionary. If you want to learn about them, please check our article on Different Ways to Iterate Through a Dictionary in C#.

Thread Safety With Dictionary

There is something worthwhile to mention here. The dictionary supports multiple reads at the same time during the enumeration. However, it doesn’t give access to writing during the enumeration. This means it doesn’t allow multiple threads to operate reading and writing at the same time. Therefore, this is not a thread-safe procedure. To find out more information about thread safety, please take a look at the documentation on Thread Safety.

Retrieve an Element With a Given Key 

When we want to fetch a value of a specific key, we first need to check if the key exists in the dictionary. We can use several ways to do this.

ContainsKey(TKey) –  this method returns true or false depending on whether the key exists in the dictionary.

Also, there is another built-in method – TryGetValue(Tkey, TValue):

if (productsDict.TryGetValue(2, out Product? product1) && product1 != null)
{
    Console.WriteLine($"Key = {2} exists, Value = {product1.ProductId}, {product1.ProductName}");
}

This method safely returns the value if the given key exists without throwing an exception. It returns false if the key doesn’t exist. If the method finds a key, it sets the assigned value to the product1 variable by using the out keyword.

The console output as a result:

Key = 2 exists, Value = 113, TV

Check our article on How to Detect if a Dictionary Key Exists in C# that explains these methods in more detail. Also, we have an article on How to Get an Item by Index from Dictionary in C# that we recommend reading.

Retrieve an Element by Using an Extension Method

In addition to the previous methods, we are going to inspect one more method – GetValueOrDefault<TKey,TValue>. This is an extension method that comes with IDictionary<TKey,TValue>. As we mentioned before, Dictionary<TKey,TValue> inherits from the IDictionary<TKey,TValue> interface. Therefore, we can use the extension methods the interface provides.

GetValueOrDefault<TKey,TValue> takes the key and returns its value. In this case, we don’t need to use the out keyword. It returns the value automatically if it exists. Otherwise, it returns the default value:

var productValue = (productsDict.GetValueOrDefault(1));

if (productValue != null)
{
    Console.WriteLine($"Key = {1} exists, Value = {productValue.ProductId}, {productValue.ProductName}");
}

We take 1 as the value of the key parameter we want to fetch from the dictionary. When we execute the code, because a key with a value of 1 exists, it returns the Product value that is mapped to it. 

We can see the output in the console window:

Key = 1 exists, Value = 112, Chair

Take a notice that we perform a null check. Especially when using reference types in the dictionary, we have to watch out for the possibility of obtaining null values. If the GrtValueOrDefault method can’t find the key in the dictionary, it would return null. As a result, we would face NullReferenceException. 

So, what is so special about this method, and why would we want to use it instead of the other methods such as TryGetValue<TKey,TValue>?

Well, with this method, we can set a default value that we want to return if the key we request doesn’t exist:

Dictionary<int, string> dict3 = new Dictionary<int, string>()
{
    {1, "Red"},
    {2, "Yellow"},
    {3, "Green"},
};

var color = (dict3.GetValueOrDefault(4, "Color not found."));
Console.WriteLine(color);

We set a default value of "Color not found.". To emphasize, the type of the default value has to match TValue type we declared in the dictionary, which is a string in this case.

As the key with a value of 4 does not exist, we can see the default value as our result.

You can explore the List of Extension Methods we can use for different scenarios.

Update Dictionary in C#

Let’s carry on with our productsDict and see how to update its elements.

We can simply update the value of an element using the Item[Key]:

productsDict[0] = new Product() { ProductId = 110, ProductName = "Desk" };

With it, we can get or set the value of the element of the given key. Accordingly, the value of the key parameter 0 changes:

Key = 0, Value = 110, Desk
Key = 1, Value = 112, Chair
Key = 2, Value = 113, TV
Key = 3, Value = 114, Lamp

As a rule of thumb, we cannot retrieve, or update a value that doesn’t exist. As well as, we cannot add an element with a key that we already added. Therefore, we should also check if the key we want to update exists using the methods we discussed. 

Remove Dictionary Elements

There is another commonly used built-in method – Remove(TKey). We use this method to remove a certain existing element:

productsDict.Remove(2);

After executing the method, the element with the key parameter value of 2 is not in the productDict anymore:

Key = 0, Value = 110, Desk
Key = 1, Value = 112, Chair
Key = 3, Value = 114, Lamp

If we want to remove all the elements from a dictionary in C#, we also have a built-in Clear() method for that:

productsDict.Clear();

Let’s check if we successfully cleared the dictionary elements. In order to check this, we will use the property – Count:

var numberOfElements = productsDict.Count;

Console.WriteLine($"Number of dictionary elements: {numberOfElements}");

This property shows us the number of elements in the dictionary.

In this case, we expect the number of elements to be 0:

Number of dictionary elements: 0

Conclusion

In this article, we have learned about Dictionary in C#.

We looked at creating and adding to a dictionary and how to retrieve, update, and remove its elements. We implemented commonly used methods and properties. We also covered some edge cases and ways to deal with exceptions.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!