Search code examples
c#dictionaryc#-6.0collection-initializer

C# 6.0's new Dictionary Initializer - Clarification


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.


Solution

  • 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:

    var dict = new Dictionary<int,string>();
    dict[3] = "foo";
    dict[42] = "bar";
    

    But using initialization syntax, you had to use braces:

    var dict = new Dictionary<int,string>
    {
        {3, "foo"},
        {42, "bar"}
    };
    

    The new C# 6 index initialization syntax makes initialization syntax more consistent with index usage:

    var dict = new Dictionary<int,string>
    { 
        [3] = "foo",
        [42] = "bar"
    };
    

    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 an Add method. That happened to work with a Dictionary<TKey,TValue>, but that doesn't mean that it worked with any index based type.