Miguel
Miguel

Reputation: 3506

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} };

Upvotes: 3

Views: 2094

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292765

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.

Upvotes: 4

Jon
Jon

Reputation: 437904

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.

Upvotes: 2

Related Questions