Using dictionaries in C# with examples - Tutorial

How To Create And Use Dictionaries In C#

by Kens Learning Curve
Using dictionaries in C# - Kens Learning Curve

Dictionaries in C# are collections of keys, values, and a well-used class. I’ll show you the class’s basics in this tutorial with examples. I’ll explain what a dictionary is, what it’s used for, and how we use them.

What Are Dictionaries In C#?

It’s basically a list but with a key and a value. In a list you only have values. The key of the dictionary can be used to quickly find a value and use it. The key needs to be unique and associated with a specific value.

Both the key and value are generic, which means you can add any type of member, class, etc. you want. It is recommended to keep the key simple, like a GUID or an integer.

Dictionaries in C# also have known methods like Add()Remove(), and Clear(). It also has methods specifically for a dictionary.

To sum it up:

  • It has a key, which cannot be NULL and needs to be unique.
  • it has a value, which can be NULL and can be duplicated.
  • The key and value are generic, which means all types of members and classes can be used.
  • The elements (key and value) are stored as a KeyValuePair

The basic usage of a dictionary looks like this:

// Fully
Dictionary<int, string> movies = new();
movies.Add(1, "The Matrix");
movies.Add(2, "Inception");
movies.Add(3, "Jaws");

// Or simplified
Dictionary<int, string> movies = new()
{
    { 1, "The Matrix" },
    { 2, "Inception" },
    { 3, "Jaws" }
};

Examples Of Dictionaries In C#

Let’s explore some of the basic functions of dictionaries in C# and add, retrieve, and delete elements from the dictionary using C# code.

Add

An example of creating dictionaries in C# is shown in the previous section. After initialization, we can still add keys and values:

Dictionary<int, string> movies = new()
{
    { 1, "The Matrix" },
    { 2, "Inception" },
    { 3, "Jaws" }
};

movies.Add(1, "The Green Latern");
movies.Add(4, "The Muppets");

Although this code is correct it gives an error when running the application:

Error With Duplicate Key - How To Create And Use Dictionaries In C# - Kens Learning Curve

As said, the key needs to be unique, and key 1 is not unique. You don’t get a compile error, it will start up. But you’ll get a run-time error. Change the second ‘1’ to ‘5’ to fix the error.

Retrieving values

There are several ways to retrieve the keys and values from dictionaries in C#. The simplest way is to use the key as if it’s an index, as shown below.

Dictionary<int, string> movies = new()
{
    { 1, "The Matrix" },
    { 2, "Inception" },
    { 3, "Jaws" }
};

movies.Add(4, "The Muppets");

Console.WriteLine($"The title of the movie with key 4 is {movies[4]}");

This code will show the title of the movie which is associated with key 4. Since I have declared the dictionary with an integer as the key, only integers are accepted if you want to get the value by key.

If the key does not exist in the dictionary an exception will be thrown. To avoid this you could check if the key exists with the ContainsKey() method, also used when removing an element. Another way is to use  TryGetValue(). This method will return true or false, whether or not the key exists. The TryGetValue() also has an out parameter that can contain the value associated with the key – when it exists.

You could also loop through a dictionary, getting all the values one by one:

Dictionary<string, string> movies = new()
{
    { "TM", "The Matrix" },
    { "IC", "Inception" },
    { "JA", "Jaws" },
    { "TMU", "The Muppets" }
};

if (movies.TryGetValue("TMU", out string value))
    Console.WriteLine($"The key TMU has the value {value}.");
else
    Console.WriteLine("Key TMU is not found.");
Dictionary<string, string> movies = new()
{
    { "TM", "The Matrix" },
    { "IC", "Inception" },
    { "JA", "Jaws" }
};

movies.Add("TMU", "The Muppets");

foreach (KeyValuePair<string, string> kvp in movies)
{
    Console.WriteLine($"The movie with key= {kvp.Key} has the title {kvp.Value}");
}

Removing elements

Removing an element from a dictionary in C# isn’t really that hard. But you should check if the key exists before removing it. If the key exists you can remove the element with that key.

Dictionary<string, string> movies = new()
{
    { "TM", "The Matrix" },
    { "IC", "Inception" },
    { "JA", "Jaws" },
    { "TMU", "The Muppets" }
};

if (movies.ContainsKey("JA"))
    movies.Remove("JA");

foreach (KeyValuePair<string, string> kvp in movies)
{
    Console.WriteLine($"The movie with key= {kvp.Key} has the title {kvp.Value}");
}

In the above example, I check if the key “JA” exists with ContainsKey(). This method returns true (key does exist) or false (key doesn’t exist). If the key exists it is safe to remove the element with Remove().

You could also use the ContainsKey() to check if a key exists before using it.

Using objects

Using objects as values is possible and not that hard to do. Although using dictionaries in C# is a great way of storing and retrieving objects, sometimes it’s better to use a different approach, like a List<T>.

A dictionary does allow it to add different types of objects as a value, but I don’t recommend it. The reason for this is simple: You have to check the type of the value, cast it, and then use it. The example below gives a small demonstration:

Dictionary<string, object> movies = new()
{
    { "TM", new Movie() { Title = "The Matrix", Rating = 5 } },
    { "IC", new Movie() { Title = "Inception", Rating = 3 } },
    { "JA", new Movie() { Title = "Jaws", Rating = 5 } },
    { "TMU", new Movie() { Title = "The Muppets", Rating = 5 } },
    { "RR", new Actor() { Name = "Ryan Reynolds" } },
    { "KR", new Actor() { Name = "Keanu Reeves" } },
};

var val = movies["KR"];
if(val.GetType() == typeof(Movie))
    Console.WriteLine($"The movie is called {((Movie)val).Title}");
else if(val.GetType() == typeof(Actor))
    Console.WriteLine($"The ACTOR is called {((Actor)val).Name}");

public class Movie
{
    public string Title { get; set; }
    public int Rating { get; set; }
}

public class Actor
{
    public string Name { get; set; }
}

I declared the dictionary with an object as the value. That means that value can be anything. I created another object; Actor. I put both movies and actors in the dictionary. If I get a value from the dictionary I have to check which type it is before I can call the properties.

Although this is doable, it will be a bit harder when you want to add more types to a dictionary. It is better to keep it simple or use something different to store your values.

Conclusion On Dictionaries In C#

Although this is a short article, it does show the impact a dictionary can have on your code. There are many scenarios where you want to use a dictionary (or not).

In some scenarios, a List<T> would be better, but when you want to keep your items unique, you need some sort of a key. A dictionary offers just that; a unique key.

Related Articles

Leave a Comment

About

Kens Learning Curve is all about learning C# and all that comes along with it. From short, practical tutorials to learning from A to Z.

 

All subjects are tried and used by myself and I don’t use ChatGPT to write the texts.

Contact

Use the contact form to contact me or send me an e-mail.

The contact form can be found here.

Email: info@kenslearningcurve.com

@2023 – All Right Reserved. Designed and Developed by Kens Learning Curve

Table Of Contents