What benefits does dictionary initializers add over collection initializers?

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

Leave a Comment