Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In a recent past there has been a lot of talk about whats new in C# 6.0
One of the most talked about feature is using Dictionary initializers in C# 6.0
But wait we have been using collection initializers to initialize the collections and can very well initialize a Dictionary also in .NET 4.0 and .NET 4.5 (Don't know about old version) like

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

So what is there new in C# 6.0, What Dictionary Initializer they are talking about in C# 6.0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
242 views
Welcome To Ask or Share your Answers For Others

1 Answer

While you could initialize a dictionary with collection initializers, it's quite cumbersome. Especially for something that's supposed to be syntactic sugar.

Dictionary initializers are much cleaner:

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

More importantly these initializers aren't just for dictionaries, they can be used for any object supporting 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...