How can I create a new instance of ImmutableDictionary?

C#.Net 4.5Immutability

C# Problem Overview


I would like to write something like this:

var d = new ImmutableDictionary<string, int> { { "a", 1 }, { "b", 2 } };

(using ImmutableDictionary from System.Collections.Immutable). It seems like a straightforward usage as I am declaring all the values upfront -- no mutation there. But this gives me error:

> The type 'System.Collections.Immutable.ImmutableDictionary<TKey,TValue>' has no constructors defined

How I am supposed to create a new immutable dictionary with static content?

C# Solutions


Solution 1 - C#

You can't create immutable collection with a collection initializer because the compiler translates them into a sequence of calls to the Add method. For example if you look at the IL code for var d = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } }; you'll get

IL_0000: newobj instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string, int32>::.ctor()
IL_0005: dup
IL_0006: ldstr "a"
IL_000b: ldc.i4.1
IL_000c: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string, int32>::Add(!0, !1)
IL_0011: dup
IL_0012: ldstr "b"
IL_0017: ldc.i4.2
IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string, int32>::Add(!0, !1)

Obviously this violates the concept of immutable collections.

Both your own answer and Jon Skeet's are ways to deal with this.

// lukasLansky's solution
var d = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } }.ToImmutableDictionary();

// Jon Skeet's solution
var builder = ImmutableDictionary.CreateBuilder<string, int>();
builder.Add("a", 1);
builder.Add("b", 2);   
var result = builder.ToImmutable();

Solution 2 - C#

Either create a "normal" dictionary first and call ToImmutableDictionary (as per your own answer), or use ImmutableDictionary<,>.Builder:

var builder = ImmutableDictionary.CreateBuilder<string, int>();
builder.Add("a", 1);
builder.Add("b", 2);
var result = builder.ToImmutable();

It's a shame that the builder doesn't have a public constructor as far as I can tell, as it prevents you from using the collection initializer syntax, unless I've missed something... the fact that the Add method returns void means you can't even chain calls to it, making it more annoying - as far as I can see, you basically can't use a builder to create an immutable dictionary in a single expression, which is very frustrating :(

Solution 3 - C#

So far I like this most:

var d = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } }.ToImmutableDictionary();

Solution 4 - C#

You could use a helper like this:

public struct MyDictionaryBuilder<TKey, TValue> : IEnumerable
{
    private ImmutableDictionary<TKey, TValue>.Builder _builder;

    public MyDictionaryBuilder(int dummy)
    {
        _builder = ImmutableDictionary.CreateBuilder<TKey, TValue>();
    }

    public void Add(TKey key, TValue value) => _builder.Add(key, value);

    public TValue this[TKey key]
    {
        set { _builder[key] = value; }
    }

    public ImmutableDictionary<TKey, TValue> ToImmutable() => _builder.ToImmutable();

    public IEnumerator GetEnumerator()
    {
        // Only implementing IEnumerable because collection initializer
        // syntax is unavailable if you don't.
        throw new NotImplementedException();
    }
}

(I'm using the new C# 6 expression-bodied members, so if you want this to compile on older versions, you'd need to expand those into full members.)

With that type in place, you can use collection initializer syntax like so:

var d = new MyDictionaryBuilder<int, string>(0)
{
    { 1, "One" },
    { 2, "Two" },
    { 3, "Three" }
}.ToImmutable();

or if you're using C# 6 you could use object initializer syntax, with its new support for indexers (which is why I included a write-only indexer in my type):

var d2 = new MyDictionaryBuilder<int, string>(0)
{
    [1] = "One",
    [2] = "Two",
    [3] = "Three"
}.ToImmutable();

This combines the benefits of both proposed advantages:

  • Avoids building a full Dictionary<TKey, TValue>
  • Lets you use initializers

The problem with building a full Dictionary<TKey, TValue> is that there is a bunch of overhead involved in constructing that; it's an unnecessarily expensive way of passing what's basically a list of key/value pairs, because it will carefully set up a hash table structure to enable efficient lookups that you'll never actually use. (The object you'll be performing lookups on is the immutable dictionary you eventually end up with, not the mutable dictionary you're using during initialization.)

ToImmutableDictionary is just going to iterate through the contents of the dictionary (a process rendered less efficient by the way Dictionary<TKey, TValue> works internally - it takes more work to do this than it would with a simple list), gaining absolutely no benefit from the work that went into building up the dictionary, and then has to do the same work it would have done if you'd used the builder directly.

Jon's code avoids this, using only the builder, which should be more efficient. But his approach doesn't let you use initializers.

I share Jon's frustration that the immutable collections don't provide a way to do this out of the box.

Edited 2017/08/10: I've had to change the zero-argument constructor to one that takes an argument that it ignores, and to pass a dummy value everywhere you use this. @gareth-latty pointed out in a comment that a struct can't have a zero-args constructor. When I originally wrote this example that wasn't true: for a while, previews of C# 6 allowed you to supply such a constructor. This feature was removed before C# 6 shipped (after I wrote the original answer, obviously), presumably because it was confusing - there were scenarios in which the constructor wouldn't run. In this particular case it was safe to use it, but unfortunately the language feature no longer exists. Gareth's suggestion was to change it into a class, but then any code using this would have to allocate an object, causing unnecessary GC pressure - the whole reason I used a struct was to make it possible to use this syntax with no additional runtime overhead.

I tried modifying this to perform deferred initialization of _builder but it turns out that the JIT code generator isn't smart enough to optimize these away, so even in release builds it checks _builder for each item you add. (And it inlines that check and the corresponding call to CreateBuilder which turns out to produce quite a lot of code with lots of conditional branching). It really is best to have a one-time initialization, and this has to occur in the constructor if you want to be able to use this initializer syntax. So the only way to use this syntax with no additional costs is to have a struct that initializes _builder in its constructor, meaning that we now need this ugly dummy argument.

Solution 5 - C#

Or this

ImmutableDictionary<string, int>.Empty
   .Add("a", 1)
   .Add("b", 2);

There is also AddRange method available.

Solution 6 - C#

You could write a custom ImmutableDictionaryLiteral class with an implicit operator to make a syntax very close to what you want.

public class ImmutableDictionaryLiteral<TKey, TValue> : Dictionary<TKey, TValue>
{
    public static implicit operator ImmutableDictionary<TKey, TValue>(ImmutableDictionaryLiteral<TKey, TValue> source)
    {
        return source.ToImmutableDictionary();
    }
}

Then you call it by declaring a ImmutableDictionary<TKey, TValue> variable and initializing with a ImmutableDictionaryLiteral<TKey, TValue> value.

ImmutableDictionary<string, string> dict = new ImmutableDictionaryLiteral<string, string>()
{
    { "key", "value" },
    { "key2", "value2" }
};

This also works with object initializer syntax

ImmutableDictionary<string, string> dict = new ImmutableDictionaryLiteral<string, string>()
{
    ["key"] = "value",
    ["key2"] = "value2"
};

Solution 7 - C#

I prefer this syntax:

var dict = ImmutableDictionaryEx.Create<int, string>(
                (1, "one"),
                (2, "two"),
                (3, "three"));

Can be easily achieved using this method:

public static class ImmutableDictionaryEx {

	/// <summary>
	/// Creates a new <see cref="ImmutableDictionary"/> with the given key/value pairs.
	/// </summary>
	public static ImmutableDictionary<K, V> Create<K, V>(params (K key, V value)[] items) where K : notnull {
		var builder = ImmutableDictionary.CreateBuilder<K, V>();
		foreach (var (key, value) in items)
			builder.Add(key, value);
		return builder.ToImmutable();
	}

}

Solution 8 - C#

There is another answer I don't see here (maybe it's a new method?):

Just use the CreateRange method to create a new ImmutableDictionary using an IEnumerable<KVP>.

// The MyObject record example
record MyObject(string Name, string OtherStuff);


// The init logic for the ImmutableDictionary
var myObjects = new List<MyObject>();
var dictionary = ImmutableDictionary
   .CreateRange(myObjects.Select(obj => new KeyValuePair<string, MyObject>(obj.Name, obj)));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLuk&#225;š L&#225;nsk&#253;View Question on Stackoverflow
Solution 1 - C#DirkView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#Lukáš LánskýView Answer on Stackoverflow
Solution 4 - C#Ian GriffithsView Answer on Stackoverflow
Solution 5 - C#Miha MarkicView Answer on Stackoverflow
Solution 6 - C#just.another.programmerView Answer on Stackoverflow
Solution 7 - C#AndiView Answer on Stackoverflow
Solution 8 - C#El MacView Answer on Stackoverflow