Dictionaries in C#

 

 

1 - What is a Dictionary in C#?

In C# we have the dictionary type, which is a collection that allows us to store data in a key-value format. It uses specific types for both its key and value through generics.

 

A dictionary is represented by the type Dictionary<TKey, TValue> and uses KeyValuePair<TKey, TValue> for each element internally.

This means that the value you assign as the Key must be unique.

 

In the past, we used Hashtable, but with the arrival of generics, we now use Dictionary. This is because, for Hashtable to work, the object was stored as type Object, which involved boxing and unboxing with each operation, and lacked the advantages of generics.

 

 

2 - Creating a Dictionary and Adding Elements in C#

To create a dictionary in C#, you simply need to instantiate it. To add elements, you can do so either at initialization or by using the .Add() method.

// initialization and assign valuesDictionary<string, string> comunidadesCapitales = new Dictionary<string, string>(){    {"Aragon", "Zaragoza"},    {"Navarra", "Pamplona"}};// add valuescomunidadesCapitales.Add("Castilla la mancha", "Toledo");

As I mentioned, the key must be unique. So the "comunidad autónoma" cannot be repeated. If you try to add "Aragon" again, an exception will be thrown.

 

 

3 - Accessing Dictionary Elements in C#

To access dictionary elements, we use the indexer. You need to use the type of key you specified when creating the dictionary.

And when you print, it returns the value:

Console.WriteLine(comunidadesCapitales["Aragon"]); // returns Zaragoza

 

If you want to access by position, you can do so with the .ElementAt(position) method.

But in this case, you will receive a KeyValuePair<TKey, TValue> type, so to print the value, you have to access .Value:

KeyValuePair<string, string> resultado = comunidadesCapitales.ElementAt(0);Console.WriteLine(resultado.Value); // returns Zaragoza

 

3.1 - The Optimal Way to Access Elements in a C# Dictionary

The most optimal way to access dictionary elements is to use .TryGetValue(). This is because if you try to access a non-existent element with the indexer, you'll get an exception, whereas with TryGetValue() you won't.

However, it works a little differently. When calling .TryGetValue(), you're checking if the value exists. The method returns a boolean (true or false).

The actual value of the element is returned through the method's out parameter:

if (comunidadesCapitales.TryGetValue("Aragon", out string resultadoCapital)){    Console.WriteLine(resultadoCapital); // Zaragoza}else{    Console.WriteLine("the key does not exist");}

 

3.2 - Updating Elements in a C# Dictionary

To access dictionary elements, we use the indexer, but we should first check if the value exists. For that, we can use the .ContainsKey() method, which returns true or false. Once we know it exists, we can change it.

if(comunidadesCapitales.ContainsKey("Aragon")){    comunidadesCapitales["Aragon"] = "Teruel Existe";}

 

3.3 - Removing Elements from a Dictionary in C#

If you want to remove elements from a dictionary, use the .Remove(key) method, but be careful, because if the key doesn't exist, you'll get an exception.

Optionally, you can use .Clear(), which will remove all elements.

comunidadesCapitales.Remove("Aragon");comunidadesCapitales.Clear();

 

 

Conclusion

In this post, we've seen how to create dictionaries and add elements

How to read elements from a dictionary

How to remove elements from a dictionary

 

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café