C# Dictionary Examples

Dictionaries are one of the most powerful collection types available in C#. They allow you to store data as key-value pairs, making lookups extremely fast and efficient.

Whether you're building APIs, web applications, inventory systems, caching solutions, or configuration managers, understanding dictionaries can significantly improve your application's performance and code quality.


What Is a Dictionary in C#?

A Dictionary stores information as key-value pairs. Each key must be unique, while values may be duplicated.

Think of a dictionary like a real-world phone book. A person's name acts as the key, while their phone number is the value associated with that key.

Dictionary<int, string> students = new Dictionary<int, string>();

In this example, the integer key represents a student ID, and the string value represents the student's name.

Creating a Dictionary

Before storing data, you must create an instance of Dictionary.

using System.Collections.Generic;

Dictionary<int, string> students =
    new Dictionary<int, string>();

You can also initialize values immediately.

Dictionary<int, string> students =
    new Dictionary<int, string>
{
    { 1, "John" },
    { 2, "Sarah" },
    { 3, "Michael" }
};

Adding Items to a Dictionary

Use the Add() method to insert new key-value pairs.

students.Add(4, "Emma");
students.Add(5, "David");

Each key must be unique. Attempting to add a duplicate key will result in an exception.

Retrieving Values

Values can be accessed directly through their keys.

string student = students[1];

Console.WriteLine(student);

Output

John

This lookup operation is typically very fast, making dictionaries ideal for searching and retrieving information.

Updating Existing Values

You can update a value by assigning a new value to an existing key.

students[1] = "John Smith";

The key remains the same while the associated value changes.

Checking Whether a Key Exists

Before retrieving a value, it's often a good idea to verify that the key exists.

if (students.ContainsKey(2))
{
    Console.WriteLine("Student found.");
}

Using ContainsKey() helps prevent runtime exceptions.

Removing Items

The Remove() method deletes a key-value pair.

students.Remove(3);

Once removed, the key and its associated value are no longer available.

Looping Through a Dictionary

A foreach loop allows you to access every key-value pair.

foreach (var item in students)
{
    Console.WriteLine(
        $"ID: {item.Key}, Name: {item.Value}");
}

Sample Output

ID: 1, Name: John
ID: 2, Name: Sarah
ID: 4, Name: Emma

This technique is useful when generating reports, displaying data, or exporting information.

Dictionary vs List

Feature Dictionary List
Lookup Speed Very Fast Slower
Uses Keys Yes No
Maintains Order Not Guaranteed Yes
Duplicate Keys No Not Applicable

Choose a Dictionary when fast lookups are important. Use a List when you mainly work with ordered collections of items.

Performance Considerations

Dictionaries use hash tables internally, allowing most lookups, insertions, and removals to execute very quickly.

  • Excellent for searching large datasets.
  • Avoid duplicate keys.
  • Use ContainsKey() before accessing unknown keys.
  • Choose meaningful key types.
  • Consider capacity settings for large collections.
Dictionary<int, string> users =
    new Dictionary<int, string>(1000);

Setting an initial capacity can reduce internal resizing operations.

Real-World Use Cases

  • User ID to User Profile mapping
  • Product ID lookup systems
  • Application configuration settings
  • Caching frequently accessed data
  • Language translation dictionaries
  • API response processing

Frequently Asked Questions

Can a Dictionary contain duplicate values?

Yes. Values can be duplicated, but keys must always be unique.

What happens if I add a duplicate key?

The Add() method throws an exception when a duplicate key is inserted.

Is Dictionary faster than List?

For lookups by key, Dictionary is generally much faster than searching through a List.

Can a Dictionary store custom objects?

Yes. Both keys and values can be custom classes or structs.

Conclusion

Dictionaries are an essential collection type for modern C# development. Their fast lookup performance and flexible key-value structure make them ideal for a wide variety of applications.

By understanding how to add, retrieve, update, remove, and iterate through dictionary data, you'll be able to write more efficient and maintainable .NET applications.