I've read that :
The team have generally been busy implementing other variations on initializers. For example you can now initialize a Dictionary object
But looking at :
var Dic = new Dictionary<string,int>{ {"x",3}, {"y",7} };
VS
var Dic = new Dictionary<string,int>{ ["x"]=3, ["y"]=7 };
I don't see where the benefit is. it looks the same. Both are nothing more than a name-value collection.
They swapped pairs of curly braces for pairs of square brackets and some commas
Question:
What is the added value for using the new syntax ? a real world example would be much appreciated.
The code in the first case uses the collection initializer syntax. To be able to use the collection initializer syntax, a class must:
Collection Initializers:
IEnumerable
interface.Add()
method. (as of C#6/VS2015, it may be an extension method)So a class defined like so may use the syntax:
Not all objects are
IEnumerable
or has an add method and therefore cannot use that syntax.On the other hand, many objects define (settable) indexers. This is where the dicionary initializer is used. It might make sense to have indexers but not necessarily be
IEnumerable
. With the dictionary initializer, you don't need to beIEnumerable
, you don't need anAdd()
method, you only need an indexer.Being able fully initialize an object in a single expression is generally useful (and in some contexts, a requirement). The dictionary initializer syntax makes it easier to do that without the steep requirements of using collection initializers.
It may be a questionable feature, but the new syntax allows you to set the same multiple times.
is allowed: here the key
"a"
has the value"c"
.In contrast, using
creates an exception:
There's no technical benefit per se; it's just syntactic sugar (like many of the new C# 6 features). The C# feature descriptions PDF, in fact, mentions only a matter of elegance:
The main advantage here with a dictionary is consistency. With a dictionary, initialization did not look the same as usage.
For example, you could do:
But using initialization syntax, you had to use braces:
The new C# 6 index initialization syntax makes initialization syntax more consistent with index usage:
However, a bigger advantage is that this syntax also provides the benefit of allowing you to initialize other types. Any type with an indexer will allow initialization via this syntax, where the old collection initializers only works with types that implement
IEnumerable<T>
and have anAdd
method. That happened to work with aDictionary<TKey,TValue>
, but that doesn't mean that it worked with any index based type.