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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With