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:

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

That’s all about initializing a Dictionary in C#.