Search code examples
c#.netconcurrencyimmutable-collections

Constructing immutable dictionary with inner immutable dictionary


I have the following dictionary and wish to make it immutable;

var dict = ConcurrentDictionary<Type, ConcurrentDictionary<Type, Action>>

I then call

var immmutableDict = dict.ToImmutableDictionary();

However this would still give the internal ConcurrentDictionary<Type, Action> dictionary i believe.

How can i make an immutable copy of the entire dictionary in a thread safe fashion with existing functions, or would i need to lock the entire operation to ensure atomic conversion?

ImmutableDictionary<Type, ImmutableDictionary<Type, Action>>

Alternatively if the above is not possible, i can refactor code to use an ReadOnlyDictionary dictionary from the start, however i face the same challenge with the inner dictionary to make it read only during construction:

var dict2 = new Dictionary<Type, Dictionary<Type, InstanceProducer>>();
/* snip perform adds to above dictionary to initialise state */

var immutableDict = dict2.ReadOnlyDictionary(); // ????
// where ReadOnlyDictionary<Type, ReadOnlyDictionary<Type, InstanceProducer>>(); is returned
// i need to make the above immutable with an immutable internal dictionary

Solution

  • You just need to convert each of the internal dictionaries into immutable dictionaries as well, and then make a new ImmutableDictionary from those.

    ImmutableDictionary<Type, ImmutableDictionary<Type, Action>> immutableDict = dict
        .ToImmutableDictionary(e => e.Key, e => e.Value.ToImmutableDictionary());