How To: Dictionary in C# Simplified

In C# programming, collections are essential for organizing and managing data. Among the various collection types, the Dictionary<TKey, TValue> class is particularly useful for storing data in key-value pairs. So why use a dictionary in C#? Let’s find out.

We’ll start off with a little example: Consider a large library. Instead of searching for a book by looking at every title (like you would in a list), you can use a catalog that points you to the book’s exact location. This is the advantage of a dictionary in C# and is applicable to other programming languages as well. It lets you link a unique key with a specific value, making data access efficient.

Understanding Key-Value Pairs of a Dictionary in C#

The core idea behind dictionaries is the key-value pair. Think of a dictionary as a box. Inside this box, you have items, each with a unique label (the key). This label helps you find the item (the value) quickly. If we contrast this to something like an array, arrays allow us to get things at specific locations very fast. So if we know the location (i.e. the position based on the order of the items in the array), we can go to that index within the array very fast. But with a dictionary, we can move away from the concept of numeric ordering to be able to quickly address items.

In C#, this is represented by the KeyValuePair<TKey, TValue> structure. Each key in a dictionary is unique, ensuring clear and unambiguous access to values. This means two values in a dictionary can’t share the same key. A little bit later we’ll see how this is actually managed, but as a user of a dictionary in C#, this is what you’ll want to keep in mind. Especially because we don’t get compile time protection here… Your program will let you know at runtime if something is misbehaving by having duplicate keys!

Keys and values in a dictionary can be of various data types, from integers and strings to custom objects. This makes dictionaries versatile and suitable for different programming needs. And, of course, just because you can use nearly anything as a key in a dictionary doesn’t necessarily mean that it’s a good key to have!

Creating and Initializing a Dictionary in C#

To start using dictionaries in C#, you first need to create an instance of the Dictionary<TKey, TValue> class. Here’s how you can do it:

// Create an empty dictionary with string keys and string values
Dictionary<string, string> capitals = new Dictionary<string, string>();

You can also initialize a dictionary with some key-value pairs right from the start:

// Initialize a dictionary with some countries and their capitals
Dictionary<string, string> countriesAndCapitals = new Dictionary<string, string>
{
  {"USA", "Washington, D.C."},
  {"UK", "London"},
  {"France", "Paris"},
  {"Germany", "Berlin"}
};

The above code creates a dictionary where country names are keys and their capitals are the corresponding values. Another variation of this is using the following syntax directly assigning the value to the key:

// Initialize a dictionary with some countries and their capitals
Dictionary<string, string> countriesAndCapitals = new Dictionary<string, string>
{
  ["USA"] = "Washington, D.C.",
  ["UK"] = "London",
  ["France"] = "Paris",
  ["Germany"] = "Berlin",
};

Check out this video for additional clarification:

YouTube player

Accessing and Modifying Values

Once you have a dictionary, you’ll want to retrieve, add, or modify the values stored in it. Here’s how you can perform these operations:

Accessing Values:

To get the value associated with a specific key:

// Returns "London"
string capitalOfUK = countriesAndCapitals["UK"];

However, if you try to access a key that doesn’t exist in the dictionary, it will throw a KeyNotFoundException. To avoid this, you can use the TryGetValue method:

if (countriesAndCapitals.TryGetValue("Spain", out string capital))
{
  Console.WriteLine($"The capital of Spain is {capital}.");
}
else
{
  Console.WriteLine("The key 'Spain' does not exist in the dictionary.");
}

Note the use of the out keyword here, which allows us to declare a variable that will be assigned a value when the method completes. It’s much like having an additional return value!

Adding and Modifying Values:

To add a new key-value pair:

countriesAndCapitals.Add("Japan", "Tokyo");

If you try to add a key that already exists, the Add method will throw an ArgumentException. To update an existing value, simply use the key:

// Changes the capital of France to Marseille
countriesAndCapitals["France"] = "Marseille";

To add or update a value without worrying about whether the key exists, you can use the indexer:

// Adds a new key-value pair if 'Italy' doesn't
// exist, otherwise updates the value
countriesAndCapitals["Italy"] = "Rome";

// therefore, we can call it again safely
countriesAndCapitals["Italy"] = "Not Rome Anymore!";

These basic operations form the foundation of working with dictionaries in C#. As you delve deeper, you’ll discover more functionalities that make dictionaries a powerful tool in C# programming. And of course, with more advanced use cases comes more opportunity for us to make mistakes and common pitfalls that we’ll want to avoid!

Conclusion

A dictionary in C# offers a versatile way to store and manage key-value pairs, making data retrieval efficient and intuitive. As we’ve seen in this introductory post, creating, initializing, and manipulating dictionaries is straightforward. By understanding these foundational concepts, you’re well on your way to harnessing the full power of dictionaries in your C# projects.

As you continue your journey in programming, you’ll find that dictionaries, with their dynamic nature and efficient look-up times, become an indispensable tool in your developer toolkit. In our upcoming posts, we’ll dive deeper into more advanced features and use cases of dictionaries, ensuring you’re well-equipped to tackle even more complex scenarios.

Stay tuned! You can ensure you don’t miss any updates if you subscribe to my weekly newsletter and have software engineering updates sent right to your inbox!

author avatar
Nick Cosentino Principal Software Engineering Manager
Principal Software Engineering Manager at Microsoft. Views are my own.

Leave a Reply