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?
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 :(
See more on this question at Stackoverflow