Earn More by Sharing What You Love
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!

Tim Corey
10m 19s
A powerful data structure in C# that is often underutilized is the dictionary. The Dictionary class is a generic collection found within the System.Collections.Generic namespace. In his video, "The Dictionary Data Structure in C# in 10 Minutes or Less," Tim Corey provides a concise and practical guide on how to effectively use dictionaries in your C# applications. This article breaks down Tim's explanations and examples, aiming to help you grasp the essentials of the C# dictionary with ease.
Tim begins by introducing the concept of a dictionary in C#. He compares it to a real-life dictionary where you look up a word (key) to find its definition (value). In C#, a dictionary is a collection of key-value pairs where each key is unique and cannot be null.
A dictionary in C# is declared using the Dictionary<TKey, TValue> syntax, allowing for efficient data storage and retrieval through key-value pairs. With a default initial capacity set during its instantiation, dictionaries can dynamically adjust as elements are added.
At (0:28), Tim starts with a basic console application to demonstrate how to create a dictionary. He uses the following code to initialize a dictionary with integers as keys and strings as values:
// Declare a dictionary with integer keys and string values
Dictionary<int, string> rookieOfTheYear = new Dictionary<int, string>();' Declare a dictionary with integer keys and string values
Dim rookieOfTheYear As New Dictionary(Of Integer, String)()Here, Dictionary<int, string> specifies that the keys will be integers (int) and the values will be strings (string). The variable rookieOfTheYear is the name of the dictionary instance. You can also use string keys by setting the key type as string.
Tim now adds elements to the dictionary at (2:08). He shows how to use the Add method to add key-value pairs:
// Add entries to the dictionary
rookieOfTheYear.Add(2000, "Mike Miller");
rookieOfTheYear.Add(2001, "Jane Doe");
rookieOfTheYear.Add(2002, "Jane Doe");
rookieOfTheYear.Add(2003, "John Smith");' Add entries to the dictionary
rookieOfTheYear.Add(2000, "Mike Miller")
rookieOfTheYear.Add(2001, "Jane Doe")
rookieOfTheYear.Add(2002, "Jane Doe")
rookieOfTheYear.Add(2003, "John Smith")In this example:
rookieOfTheYear.Add(2000, "Mike Miller") adds the specified key 2000 with the value "Mike Miller".2001, 2002, and 2003 are associated with "Jane Doe", "Jane Doe", and "John Smith" respectively.He notes that while values can be repeated, keys must be unique. Attempting to add a duplicate key results in an exception:
rookieOfTheYear.Add(2001, "Jane Doe"); // This will throw an exceptionrookieOfTheYear.Add(2001, "Jane Doe") ' This will throw an exceptionThis exception occurs because the key 2001 already exists in the dictionary.
To demonstrate value retrieval, Tim uses the following line of code at (3:45):
// Accessing a value with a specific key
Console.WriteLine(rookieOfTheYear[2002]); // Outputs: Jane Doe' Accessing a value with a specific key
Console.WriteLine(rookieOfTheYear(2002)) ' Outputs: Jane DoeHere, rookieOfTheYear[2002] accesses the value associated with the key 2002. This is a very efficient way to look up values based on keys.

At (4:29), Tim discusses how to check if a key exists in the dictionary using the ContainsKey method:
// Check if a key exists before accessing its value
if (rookieOfTheYear.ContainsKey(2002))
{
Console.WriteLine(rookieOfTheYear[2002]);
}' Check if a key exists before accessing its value
If rookieOfTheYear.ContainsKey(2002) Then
Console.WriteLine(rookieOfTheYear(2002))
End IfIn the above example, ContainsKey(2002) checks if the key 2002 exists in the dictionary. If it does, the corresponding value ("Jane Doe") is printed.
If the key does not exist, the dictionary returns no output, preventing errors from accessing non-existent keys.
Tim expands on dictionary capabilities at (5:33), creating a more complex example with a dictionary that maps strings to lists of strings:
// Declare a dictionary with string keys and List<string> as values
Dictionary<string, List<string>> wishList = new();
// Add entries to the dictionary with lists as values
wishList.Add("Tim Corey", new List<string> { "Xbox", "Tesla", "Pizza" });
wishList.Add("Billy Bob", new List<string> { "PS5", "Ford", "Hoagie" });
wishList.Add("Mary Jane", new List<string> { "House", "Car", "Sub" });' Declare a dictionary with string keys and List(Of String) as values
Dim wishList As New Dictionary(Of String, List(Of String))()
' Add entries to the dictionary with lists as values
wishList.Add("Tim Corey", New List(Of String) From {"Xbox", "Tesla", "Pizza"})
wishList.Add("Billy Bob", New List(Of String) From {"PS5", "Ford", "Hoagie"})
wishList.Add("Mary Jane", New List(Of String) From {"House", "Car", "Sub"})Here:
At (7:24), Tim demonstrates how to iterate over a dictionary using a foreach loop:
// Iterate over each key-value pair in the dictionary
foreach (var (key, value) in wishList)
{
Console.WriteLine($"{key}'s wish list:");
// Iterate over each item in the list of values
foreach (var item in value)
{
Console.WriteLine($"\t{item}");
}
}' Iterate over each key-value pair in the dictionary
For Each kvp In wishList
Dim key = kvp.Key
Dim value = kvp.Value
Console.WriteLine($"{key}'s wish list:")
' Iterate over each item in the list of values
For Each item In value
Console.WriteLine(vbTab & item)
Next
NextIn this example:
foreach (var (key, value) in wishList) iterates over each key-value pair in the wishList dictionary.key refers to the key (e.g., "Tim Corey").value refers to the list of values associated with that key.This allows for printing all the elements using a loop to access dictionary elements one by one with a specified key and its corresponding specified value. Here is the output:

Tim also shows how to access more complex values in the dictionary by explicitly using the specified index at (8:26):
// Access the first item in the list of values for the specified key
Console.WriteLine(wishList["Tim Corey"][0]); // Outputs: Xbox' Access the first item in the list of values for the specified key
Console.WriteLine(wishList("Tim Corey")(0)) ' Outputs: XboxHere, wishList["Tim Corey"] accesses the list associated with the key "Tim Corey", and [0] retrieves the first item in that list.
Tim concludes at (9:00) by emphasizing the importance of understanding dictionaries. He points out that while dictionaries may not be used frequently, they are incredibly useful for scenarios requiring unique keys and efficient lookups.
By following Tim Corey's video, you can master the use of dictionaries in C#, enhancing your programming toolkit for scenarios requiring efficient data retrieval and storage. Check out Tim's channel for more informative videos on C#.
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!
Join our newsletter, you’ll get exclusive access on article updates. We value your privacy