C# Dictionary<TKey,TValue> Collection Tutorial
Quick Answer
The C# Dictionary<TKey,TValue> is a generic collection that stores key-value pairs, allowing fast lookups, additions, and removals by key. It is ideal for scenarios where you need to associate unique keys with values and retrieve them efficiently.
Learning Objectives
- Explain the purpose of Dictionary<TKey,TValue> in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Dictionary<TKey,TValue>.
- Apply Dictionary<TKey,TValue> in a simple real-world scenario or practice task.
Introduction to Dictionary<TKey,TValue> in C#
In C#, collections are essential for managing groups of related objects. One powerful collection type is the Dictionary<TKey,TValue>, which stores data as key-value pairs.
This tutorial introduces the Dictionary<TKey,TValue> collection, explaining its purpose, usage, and benefits with clear examples and best practices.
A dictionary is a collection of keys and values, where each key is unique.
What is Dictionary<TKey,TValue>?
Dictionary<TKey,TValue> is a generic collection in C# that stores elements as pairs of keys and values. Each key must be unique, and it maps to a corresponding value.
It provides fast retrieval of values based on their keys, making it ideal for scenarios where quick lookups are required.
- Generic collection: supports any data types for keys and values.
- Keys must be unique within the dictionary.
- Values can be duplicated or null depending on the type.
- Uses a hash table internally for efficient lookups.
Creating and Initializing a Dictionary
You can create a Dictionary by specifying the types for keys and values. Initialization can be done using the constructor or collection initializer syntax.
- Use `new Dictionary<TKey, TValue>()` to create an empty dictionary.
- Use collection initializer syntax to add elements at creation.
Example: Creating a Dictionary
Here is how to create and initialize a dictionary that maps strings to integers.
Adding, Accessing, and Removing Elements
You can add elements using the Add method or indexer syntax. Access values by key using the indexer. Remove elements by key using the Remove method.
- Add elements with `Add(key, value)` or `dictionary[key] = value`.
- Access values with `dictionary[key]`.
- Check if a key exists with `ContainsKey(key)`.
- Remove elements with `Remove(key)`.
Common Operations and Methods
Dictionary<TKey,TValue> provides several useful methods and properties for working with key-value pairs.
- `Count` - gets the number of elements.
- `Clear()` - removes all elements.
- `TryGetValue(key, out value)` - safely retrieves a value without throwing exceptions.
- `Keys` and `Values` properties to enumerate keys or values.
Performance Considerations
Dictionary<TKey,TValue> offers average O(1) time complexity for lookups, additions, and removals, making it very efficient for large datasets.
However, performance depends on a good hash function for the key type to minimize collisions.
- Use immutable and well-distributed key types for best performance.
- Avoid modifying keys after insertion.
- Consider capacity and load factor when creating large dictionaries.
Practical Example
This example creates a dictionary mapping names to phone numbers, adds entries, accesses values, checks for keys, and removes an entry.
TryGetValue safely attempts to get a value by key without throwing an exception if the key does not exist.
Examples
var phoneBook = new Dictionary<string, string>()
{
{"Alice", "555-1234"},
{"Bob", "555-5678"}
};
// Add a new entry
phoneBook.Add("Charlie", "555-9012");
// Access a value
string aliceNumber = phoneBook["Alice"];
// Check if a key exists
if (phoneBook.ContainsKey("Bob"))
{
Console.WriteLine("Bob's number: " + phoneBook["Bob"]);
}
// Remove an entry
phoneBook.Remove("Alice");This example creates a dictionary mapping names to phone numbers, adds entries, accesses values, checks for keys, and removes an entry.
if (phoneBook.TryGetValue("David", out string number))
{
Console.WriteLine("David's number: " + number);
}
else
{
Console.WriteLine("David not found in phone book.");
}TryGetValue safely attempts to get a value by key without throwing an exception if the key does not exist.
Best Practices
- Always check if a key exists before accessing to avoid exceptions.
- Use TryGetValue for safe retrieval of values.
- Choose key types with good hash code implementations.
- Avoid modifying keys after adding them to the dictionary.
- Initialize dictionary capacity if size is known to improve performance.
Common Mistakes
- Accessing a key that does not exist without checking, causing exceptions.
- Using mutable objects as keys which can change hash codes.
- Ignoring performance implications of large dictionaries without capacity settings.
- Adding duplicate keys which throws exceptions.
Hands-on Exercise
Create a Student Grades Dictionary
Create a Dictionary<string, double> to store student names and their grades. Add at least five students, then retrieve and print a specific student's grade.
Expected output: Printed grade of the specified student.
Hint: Use Add() or collection initializer to add entries. Use the indexer or TryGetValue to access grades.
Safe Lookup with TryGetValue
Modify the previous exercise to safely retrieve a student's grade using TryGetValue and handle the case when the student is not found.
Expected output: Prints the grade if found, otherwise a not found message.
Hint: Use TryGetValue method and check the returned boolean.
Interview Questions
What is the difference between Dictionary<TKey,TValue> and Hashtable in C#?
InterviewDictionary<TKey,TValue> is a generic collection providing type safety and better performance, while Hashtable is non-generic and stores keys and values as objects.
How does Dictionary<TKey,TValue> handle key collisions?
InterviewDictionary<TKey,TValue> uses a hash table internally and resolves collisions using chaining or probing to store multiple keys with the same hash code.
What happens if you try to add a duplicate key to a Dictionary?
InterviewAdding a duplicate key using Add() throws an ArgumentException. Using the indexer overwrites the existing value.
MCQ Quiz
1. What is the best first step when learning Dictionary<TKey,TValue>?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Dictionary<TKey,TValue>?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. The C# Dictionary<TKey,TValue> is a generic collection that stores key-value pairs, allowing fast lookups, additions, and removals by key.
B. Dictionary<TKey,TValue> never needs examples
C. Dictionary<TKey,TValue> is unrelated to practical work
D. Dictionary<TKey,TValue> should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- The C# Dictionary<TKey,TValue> is a generic collection that stores key-value pairs, allowing fast lookups, additions, and removals by key.
- It is ideal for scenarios where you need to associate unique keys with values and retrieve them efficiently.
- In C#, collections are essential for managing groups of related objects.
- One powerful collection type is the Dictionary<TKey,TValue>, which stores data as key-value pairs.
- This tutorial introduces the Dictionary<TKey,TValue> collection, explaining its purpose, usage, and benefits with clear examples and best practices.
Summary
The Dictionary<TKey,TValue> collection in C# is a versatile and efficient way to store and retrieve data using unique keys.
It supports fast lookups, additions, and removals with a simple API and is widely used in real-world applications.
Understanding how to use Dictionary properly, including best practices and common pitfalls, is essential for effective C# programming.
Frequently Asked Questions
Can Dictionary<TKey,TValue> have null keys?
No, Dictionary<TKey,TValue> does not allow null keys. Attempting to add a null key throws an ArgumentNullException.
Is Dictionary<TKey,TValue> thread-safe?
No, Dictionary<TKey,TValue> is not thread-safe for concurrent read/write operations. Use ConcurrentDictionary for thread-safe scenarios.
How do I iterate over all key-value pairs in a Dictionary?
You can use a foreach loop over the dictionary, which iterates over KeyValuePair<TKey,TValue> elements.
What is Dictionary<TKey,TValue>?
The C# Dictionary<TKey,TValue> is a generic collection that stores key-value pairs, allowing fast lookups, additions, and removals by key.
Why is Dictionary<TKey,TValue> important?
It is ideal for scenarios where you need to associate unique keys with values and retrieve them efficiently.
How should I practice Dictionary<TKey,TValue>?
In C#, collections are essential for managing groups of related objects.

