Initialization of  Dictionary – Dictionary initializer in C# 6.0

Initialization of Dictionary – Dictionary initializer in C# 6.0

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

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

6 Comments to “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.

Comments are closed.