Dictionaries are fundamental data structures that allow you to store and retrieve data using key-value pairs. They provide efficient lookups, making them ideal for scenarios where you need to quickly access data based on a unique identifier. In this lesson, we'll explore the concept of dictionaries in C#, how to create and manipulate them, and their advantages over other data structures like lists and arrays in specific situations. Understanding dictionaries is crucial for building efficient and scalable applications.

Understanding Dictionaries: Key-Value Pairs

A dictionary, in its simplest form, is a collection of key-value pairs. Each key is unique within the dictionary, and it's used to access its corresponding value. Think of it like a real-world dictionary where you look up a word (the key) to find its definition (the value).

Key Concepts

Creating Dictionaries in C#

In C#, dictionaries are implemented using the Dictionary<TKey, TValue> class, where TKey represents the data type of the keys and TValue represents the data type of the values.

// Creating a dictionary with string keys and integer values
Dictionary<string, int> studentAges = new Dictionary<string, int>();

// Creating a dictionary with integer keys and string values
Dictionary<int, string> employeeNames = new Dictionary<int, string>();

Adding and Accessing Elements

You can add elements to a dictionary using the Add() method or by using the indexer syntax.

Dictionary<string, string> countryCodes = new Dictionary<string, string>();

// Adding elements using the Add() method
countryCodes.Add("USA", "1");
countryCodes.Add("Canada", "1");
countryCodes.Add("UK", "44");

// Adding elements using the indexer syntax
countryCodes["Germany"] = "49";
countryCodes["France"] = "33";

// Accessing elements using the indexer syntax
string usaCode = countryCodes["USA"]; // usaCode will be "1"
Console.WriteLine($"The country code for USA is: {usaCode}");

//Trying to access a key that doesn't exist will throw an exception
//string japanCode = countryCodes["Japan"]; //This will throw a KeyNotFoundException if "Japan" is not in the dictionary

Handling KeyNotFoundException

As shown in the previous example, attempting to access a key that doesn't exist in the dictionary will throw a KeyNotFoundException. To avoid this, you can use the ContainsKey() method to check if a key exists before accessing it, or use the TryGetValue() method to safely retrieve a value.

Dictionary<string, string> countryCodes = new Dictionary<string, string>();
countryCodes.Add("USA", "1");
countryCodes.Add("Canada", "1");
countryCodes.Add("UK", "44");

// Using ContainsKey() to check if a key exists
if (countryCodes.ContainsKey("Japan"))
{
    Console.WriteLine($"The country code for Japan is: {countryCodes["Japan"]}");
}
else
{
    Console.WriteLine("Country code for Japan not found.");
}

// Using TryGetValue() to safely retrieve a value
if (countryCodes.TryGetValue("UK", out string ukCode))
{
    Console.WriteLine($"The country code for UK is: {ukCode}"); //ukCode will be "44"
}
else
{
    Console.WriteLine("Country code for UK not found.");
}

Removing Elements

You can remove elements from a dictionary using the Remove() method, which takes the key of the element to be removed as an argument.