Initialize a Dictionary in C#
This post will discuss how to initialize a dictionary in C#.
1. Collection Initializer
To initialize a dictionary, we can enclose each set of key-value in curly braces. Internally for each pair, the compiler makes a call to Dictionary’s Add() method. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, string> dict = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }; foreach (var (key, value) in dict) { Console.WriteLine(key + " : " + value); } } } /* Output: key1 : value1 key2 : value2 */ |
2. Index Initializer
We can also initialize a dictionary using an index initializer, as shown below. Internally, it uses the read/write indexer method of the Dictionary class.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, string> dict = new Dictionary<string, string> { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3" }; foreach (var (key, value) in dict) { Console.WriteLine(key + " : " + value); } } } /* Output: key1 : value1 key2 : value2 key3 : value3 */ |
3. Dictionary Builder
To create a dictionary with several entries, it’s better to create a type-safe DictionaryBuilder class. Then we can use Builder’s Add() method, which takes key-value pairs instead of a dictionary. The Add() associates key with value in the built dictionary.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
using System; using System.Collections.Generic; public class DictionaryBuilder<K, V> { private Dictionary<K, V> dictionary = new Dictionary<K, V>(); public DictionaryBuilder() {} public DictionaryBuilder(Dictionary<K, V> dictionary) { this.dictionary = dictionary; } public DictionaryBuilder<K, V> Add(K key, V value) { if (dictionary == null) { throw new InvalidOperationException(); } dictionary.Add(key, value); return this; } public Dictionary<K, V> Build() { Dictionary<K, V> _ref = dictionary; dictionary = null; return _ref; } } public class Example { public static void Main() { Dictionary<string, string> dict = new DictionaryBuilder<string, string>() .Add("key1", "value1") .Add("key2", "value2") .Build(); foreach (var (key, value) in dict) { Console.WriteLine(key + " : " + value); } } } /* Output: key1 : value1 key2 : value2 */ |
That’s all about initializing a Dictionary in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)