Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable Dictionary<TKey, TValue>

How would you implement constructors for an immutable Dictionary<TKey, TValue>-like class?

Also, is it possible to allow users to use the syntax:

ImmutableDic<int, int> Instance = new ImmutableDic<int, int> { {1, 2}, {2, 4}, {3,1} };
like image 891
Miguel Avatar asked Jan 24 '26 09:01

Miguel


2 Answers

The simplest solution is to write a constructor that accepts a mutable IDictionary<TKey, TValue>. Build the mutable dictionary and just pass it to the constructor of your immutable dictionary:

var data = new Dictionary<int, int> { {1, 2}, {2, 4}, {3,1} };
var instance = new ImmutableDic<int, int>(data);

As explained in BoltClock's comment, the initializer syntax can't be used with an immutable dictionary, since it requires an Add method.

like image 193
Thomas Levesque Avatar answered Jan 25 '26 23:01

Thomas Levesque


Have the constructor accept an IEnumerable<KeyValuePair<TKey, TValue>>.

This way, you can do:

var Instance = new ImmutableDic<int, int>(
   new Dictionary<int, int> {1, 2}, {2, 4}, {3,1} });

You can construct with the "minimal" addition of "new Dictionary", and you can also use any other way that is convenient and produces such an enumerable sequence.

like image 39
Jon Avatar answered Jan 25 '26 21:01

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!