This post will discuss how to create an immutable dictionary in C#.

The ImmutableDictionary<TKey,TValue> class represents an immutable, unordered collection of keys and values in C#. However, you can’t create an immutable dictionary with the standard initializer syntax, since the compiler internally translates each key/value pair into chains of the Add() method.

1. Using ToImmutableDictionary() Method

We can use ToImmutableDictionary() method to construct an immutable dictionary from a sequence of key/value pairs. The following method demonstrates how to use the ToImmutableDictionary method for converting an existing mutable Dictionary<TKey,TValue> to ImmutableDictionary<TKey,TValue>.

Download  Run Code

2. Using ImmutableDictionary<TKey,TValue>.Builder

Another option is to create a new immutable dictionary builder ImmutableDictionary<TKey,TValue>.Builder and use the ToImmutable() method to construct an immutable dictionary based on the contents of the builder instance. For example,

Download  Run Code

3. Using ImmutableDictionary<TKey,TValue>.Add() Method

Finally, you have the Add() method that adds the specified key/value pair to the immutable dictionary. Since it returns a new immutable dictionary that contains the additional key/value pair, we can chain multiple calls together. However, this approach is not preferable since it ends up creating a new immutable dictionary instance every time the Add() method is invoked.

Download  Run Code

That’s all about immutable dictionary in C#.