How to Add to Dictionary in C#: Syntax and Examples
In C#, you add items to a
Dictionary using the Add(key, value) method or by assigning a value to a key using dictionary[key] = value. The Add method throws an error if the key exists, while the indexer updates or adds the key-value pair.Syntax
There are two main ways to add items to a Dictionary<TKey, TValue> in C#:
Add(key, value): Adds a new key-value pair. Throws an exception if the key already exists.dictionary[key] = value: Adds or updates the value for the given key.
csharp
dictionary.Add(key, value); dictionary[key] = value;
Example
This example shows how to create a dictionary, add items using both Add and the indexer, and print the contents.
csharp
using System; using System.Collections.Generic; class Program { static void Main() { var dictionary = new Dictionary<string, int>(); // Add using Add method dictionary.Add("apple", 3); // Add or update using indexer dictionary["banana"] = 5; dictionary["apple"] = 4; // updates value for "apple" foreach (var item in dictionary) { Console.WriteLine($"{item.Key}: {item.Value}"); } } }
Output
apple: 4
banana: 5
Common Pitfalls
Using Add with a key that already exists causes an ArgumentException. To avoid this, check if the key exists with ContainsKey before adding, or use the indexer to update or add safely.
csharp
var dictionary = new Dictionary<string, int>(); dictionary.Add("key1", 1); // Wrong: Adding same key again throws exception // dictionary.Add("key1", 2); // Throws ArgumentException // Right: Check before adding if (!dictionary.ContainsKey("key1")) { dictionary.Add("key1", 2); } // Or use indexer to add or update dictionary["key1"] = 2;
Quick Reference
| Method | Description | Behavior if Key Exists |
|---|---|---|
| Add(key, value) | Adds a new key-value pair | Throws ArgumentException |
| dictionary[key] = value | Adds or updates the key-value pair | Updates existing value or adds new key |
Key Takeaways
Use dictionary.Add(key, value) to add new items but avoid duplicate keys.
Use dictionary[key] = value to add or update items safely.
Check dictionary.ContainsKey(key) before adding with Add to prevent errors.
Indexer syntax is simpler for adding or updating dictionary entries.