Initializing dictionary is not something new, you can simply initialize a dictionary by collection initializer, which is a feature from c#3.0. Collection initializer Add a parameter to do key, a parameter as the value of the corresponding key. C#6.0 adds a capability to use key/indexer in initialization to map value directly to key and value.
The following code shows how collection initializer initializes the dictionary.
dictionary<int,string> students =Newdictionary<int,string> { {1,"Student 1" }, {2,"Student 2" }, {3,"Student 3" }, {4,"Student 4" }};
View Code
This defines a Dictionary object named students, which has a list of students with a key of type int, as shown in:
In C # 6.0, with the new dictionary Initializer, the following code block will do the same:
dictionary<int,string> students =Newdictionary<int,string> { [1] ="Student 1" , [2] ="Student 2", [3] ="Student 3", [4] ="Student 4",};
View Code
The above code returns the same result, and the difference is their method of assignment. In c#6.0, it seems that we get them through indexer. And that makes the code more understandable.
Now, if you want to add a new element to collection, you can use the following method.
students[5"Student 5"; students[6"Student 6 ";
The code above adds two new elements to the dictionary.
C # 6.0: the new dictionary Initializer