Dictionary Initializers (Index Initializers) in C# 6.0

C# 6.0 Features Series

The Object Initializer is one of the useful feature that lets the developers to initialize properties of the objects or collections when declaring them.

With the earlier version of C# 6.0 , initializing the dictionary entries with collection initializer was less elegant. It included adding many flower brackets as shown below.

Dictionary<string, Employee> Developers = new Dictionary<string, Employee>
{
    { "Senthil" ,  new Employee { FirstName = "Senthil", LastName = "Kumar" } },
    { "Norton",  new Employee { FirstName = "Norton", LastName = "Stanley" }},
    { "Rupam",  new Employee { FirstName = "Rupam", LastName = "Khaitan" }},
    { "F5Debug",  new Employee { FirstName = "Karthikeyan", LastName = "Anbarasan" } },
    { "Ashok",  new Employee { FirstName = "Ashok", LastName = "Kumar" }},
};

Dictionary Initializers (Index Initializers) in C# 6.0

The new syntax in C# 6.0 allows the developers to set values through indexer which the new object contains as shown below.

Dictionary<string, Employee> Developers1 = new Dictionary<string, Employee>
{
    ["Senthil"] = new Employee { FirstName = "Senthil", LastName = "Kumar" },
    ["Norton"] = new Employee { FirstName = "Norton", LastName = "Stanley" },
    ["Rupam"] = new Employee { FirstName = "Rupam", LastName = "Khaitan" },
    ["Karthikeyan"] = new Employee { FirstName = "Karthikeyan", LastName = "Anbarasan" },
    ["Ashok"] = new Employee { FirstName = "Ashok", LastName = "Kumar" },
};

image
When we look at the code generated using the decompiled tool , you will notice that by default, the collection initializer uses the “Add” method of the Dictionary where as the new Dictionary Initializer uses the Indexer as shown in the below screenshot.

image

No Responses

Leave a Reply