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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...