Immutable Dictionary in C#
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>.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Generic; using System.Collections.Immutable; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { { "A", 1 }, { "B", 2 }, { "C", 3 } }; ImmutableDictionary<string, int> immutableDict = dict.ToImmutableDictionary(); Console.WriteLine(String.Join(", ", immutableDict)); // [A, 1], [B, 2], [C, 3] } } |
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,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Immutable; public class Example { public static void Main() { var builder = ImmutableDictionary.CreateBuilder<string, int>(); builder.Add("A", 1); builder.Add("B", 2); builder.Add("C", 3); ImmutableDictionary<string, int> immutableDict = builder.ToImmutable(); Console.WriteLine(String.Join(", ", immutableDict)); // [A, 1], [B, 2], [C, 3] } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Immutable; public class Example { public static void Main() { ImmutableDictionary<string, int> immutableDict = ImmutableDictionary<string, int>.Empty .Add("A", 1) .Add("B", 2) .Add("C", 3); Console.WriteLine(String.Join(", ", immutableDict)); // [B, 2], [C, 3], [A, 1] } } |
That’s all about immutable 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 :)