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

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...