Initialization of Dictionary – Dictionary initializer in C# 6.0

By | December 11, 2014

Initialization of Dictionary is not a new thing. You can easily initialize a Dictionary Object using a Collection Initializer, which is there since C# 3.0. Collection initializer adds one of the  parameter as Key and another as  Value corresponding to the assigned Key. C# 6.0 adds a new ability to use the Key / indexer to map with the Values directly during the initialization itself.

Following snippets shows how collection initializer initialize a dictionary object.

Dictionary<int, string> students = new Dictionary<int, string> {
{1, "Student 1" },
{2, "Student 2" },
{3, "Student 3" },
{4, "Student 4" }
};

This will define a dictionary object “students” with list of students and Key has been consider as an integer as shown in below image:

image

In C# 6.0,  with new Dictionary Initializer the following code block will also work in the same way:

Dictionary<int, string> students = new Dictionary<int, string> {
[1] = "Student 1" ,
[2] = "Student 2",
[3] = "Student 3",
[4] = "Student 4",
};

image

If you observe both of the snippets returning us the same same output, a students dictionary object. The difference is the way it has been assigned in C# 6.0, which looks similar to how we access them using indexer and makes the code easy to read and understandable.

Now, if you want to add new elements in the collection you can use easily do them as follows:

students[5] = "Student 5";
students[6] = "Student 6";

Above code will add another two elements in the dictionary .

image

6 thoughts on “Initialization of Dictionary – Dictionary initializer in C# 6.0

  1. Dhirendra Joshi

    Nice info Abhijit. I follow your daily article. They are short, sweet and informative. keep posting.

  2. Pingback: 10 New features of C# 6.0 that you should know | Abhijit's World of .NET

  3. Pingback: Top 10 Most Popular .NET Tips of the Year – From Daily .NET Tips | Abhijit's World of .NET

  4. Pingback: Top 10 Most Popular .NET Tips of the Year

Comments are closed.