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:
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", };
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 .
Nice info Abhijit. I follow your daily article. They are short, sweet and informative. keep posting.
Thanks mate !
Pingback: 10 New features of C# 6.0 that you should know | Abhijit's World of .NET
Thanks for a next good article about c# 6.0
Pingback: Top 10 Most Popular .NET Tips of the Year – From Daily .NET Tips | Abhijit's World of .NET
Pingback: Top 10 Most Popular .NET Tips of the Year