What benefits do dictionary initializers add to collection initializers?

There has been a lot of talk in the recent past about what's new in C # 6.0
One of the most talked about features is using Dictionary initializers in C # 6.0
But wait, we used collection initializers to initialize collections and we can very well initialize the Dictionary also in .NET 4.0 and .NET 4.5 (I don't know about the old version), for example

 Dictionary<int, string> myDict = new Dictionary<int, string>() { { 1,"Pankaj"}, { 2,"Pankaj"}, { 3,"Pankaj"} }; 

So what's new in C # 6.0, what kind of dictionary initializer do they say in C # 6.0

+44
collections dictionary c # collection-initializer
Dec 02 '14 at 7:37
source share
2 answers

While you can initialize a dictionary with collection initializers, this is pretty cumbersome. Especially for something that should be syntactic sugar.

Dictionary initializers are much cleaner:

 var myDict = new Dictionary<int, string> { [1] = "Pankaj", [2] = "Pankaj", [3] = "Pankaj" }; 

Moreover, these initializers are not only for dictionaries, they can be used for any object that supports an indexer , for example List<T> :

 var array = new[] { 1, 2, 3 }; var list = new List<int>(array) { [1] = 5 }; foreach (var item in list) { Console.WriteLine(item); } 

Output:

 1 5 3 
+71
Dec 02 '14 at 7:47
source share

New creates a dictionary this way

 Dictionary<int, string> myDict = new Dictionary<int, string>() { [1] = "Pankaj", [2] = "Pankaj", [3] = "Pankaj" }; 

with style <index> = <value>

Deprecated: syntax syntax with string (as indicated in comments)

 Dictionary<int, string> myDict = new Dictionary<int, string>() { $1 = "Pankaj", $2 = "Pankaj", $3 = "Pankaj" }; 

Adapted from C # 6.0 Language Preview

To understand the $ operator, take a look at the call to the AreEqual function. Pay attention to the call of the dictionary member "$ Boolean" in the builtInDataTypes variable, even though the logical element does not exist in the dictionary. Such an explicit member is not required because the $ operator invokes the indexed member in the dictionary, the equivalent of calling buildInDataTypes ["Boolean"].

+2
Dec 02 '14 at 7:47
source share



All Articles