How to Create Dictionary in C# - Simple Guide
In C#, you create a dictionary using the
Dictionary<TKey, TValue> class by specifying key and value types. You can initialize it with new Dictionary<TKey, TValue>() and add items using the Add method or indexer.Syntax
The basic syntax to create a dictionary in C# is:
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();creates an empty dictionary.TKeyis the type of keys (like strings or integers).TValueis the type of values stored.
You add items with dict.Add(key, value); or dict[key] = value;.
csharp
Dictionary<string, int> ages = new Dictionary<string, int>();
Example
This example shows how to create a dictionary, add items, and print them.
csharp
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> ages = new Dictionary<string, int>(); ages.Add("Alice", 30); ages["Bob"] = 25; foreach (var person in ages) { Console.WriteLine($"{person.Key} is {person.Value} years old."); } } }
Output
Alice is 30 years old.
Bob is 25 years old.
Common Pitfalls
Common mistakes when creating dictionaries include:
- Adding a key that already exists causes an exception.
- Using
dict[key] = value;will overwrite existing values without error. - Trying to access a key that does not exist throws a
KeyNotFoundException.
To avoid errors, check if a key exists with ContainsKey before adding or accessing.
csharp
var dict = new Dictionary<string, int>(); dict.Add("key1", 1); // dict.Add("key1", 2); // This throws an exception dict["key1"] = 3; // This overwrites the value if (dict.ContainsKey("key2")) { Console.WriteLine(dict["key2"]); } else { Console.WriteLine("Key not found."); }
Output
Key not found.
Quick Reference
| Operation | Code Example | Description |
|---|---|---|
| Create empty dictionary | var dict = new Dictionary | Creates an empty dictionary with string keys and int values. |
| Add item | dict.Add("key", 100); | Adds a new key-value pair; throws if key exists. |
| Add or update item | dict["key"] = 100; | Adds or updates the value for the key. |
| Check key exists | dict.ContainsKey("key") | Returns true if the key is in the dictionary. |
| Access value | var val = dict["key"]; | Gets the value for the key; throws if key missing. |
Key Takeaways
Use Dictionary to create dictionaries with specific key and value types.
Add items with Add() or indexer syntax; Add() throws if key exists, indexer overwrites.
Check for keys with ContainsKey() to avoid exceptions when accessing values.
Accessing a missing key throws KeyNotFoundException, so always verify key presence.
Dictionaries store unique keys and allow fast lookup of values by key.