Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I initialize a BCL immutable collection using braces?

In the old days, we could conveniently initialize mutable collections using braces, as in the following example:

var myDictionary = new Dictionary<string, decimal> {{"hello", 0m}, {"world", 1m}};

Is there a similar syntax that can be used with BCL immutable collections? I understand it is still a pre-release but maybe there is a recommended syntax, or at least this question will serve as feedback to implement these convenient initializers.

In the mean time, the shortest I have found is the following:

var myDictionary = new Dictionary<string, decimal> {{"hello", 0m}, {"world", 1m}}.ToImmutableDictionary();
like image 394
Erwin Mayer Avatar asked Jun 02 '13 11:06

Erwin Mayer


1 Answers

Is there a similar syntax that can be used with BCL immutable collections?

Not as far as I'm aware - unfortunately both object and collection initializers rely on mutability. In that respect it's a shame that the language isn't designed such that if there's an Add method with a return value, that can be used as an intermediate value. (That wouldn't help with setting properties in object initializers, mind you, and I prefer the name Plus to Add to make the semantics clearer.)

I think the approach you're already using is the most appropriate one for a shortcut.

For ImmutableList it's slightly simpler:

var list = ImmutableList.Create(1, 2, 3);

which is fairly simple (and allows for type inference) but I don't know of anything similar for ImmutableDictionary. There's an overload of Create which takes an IEnumerable<TKey, TValue>, but constructing any implementation is likely to be as fiddly as just constructing the mutable dictionary as you're already doing.

like image 68
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet