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
Just to stress the most important difference, dictionary initializer calls the indexer, and hence it performs an update when duplicate keys are encountered, whereas collection initializer calls the Add
method which will throw.
To briefly summarize the differences in general:
Collection initializer calls
Add
method (for IEnumerables) where as dictionary initializer calls indexer. This has the Add vs Update semantic differences for dictionaries.-
Dictionary initializer is technically an object initializer, hence can be mixed with initializing other properties. For e.g.:
new Dictionary<int, string> { [1] = "Pankaj", [2] = "Pankaj", [3] = "Pankaj", Capacity = 100, };
but not
new Dictionary<int, string>() { { 1,"Pankaj" }, { 2,"Pankaj" }, { 3,"Pankaj" }, Capacity = 100, // wont compile };
Being just an object initializer, indexed initializer can be used for any class with an indexer, whereas collection initializer can be used only for IEnumerables, which should be obvious anyway.
Collection initializer can be enhanced with custom
Add
extension methods, whereas ditionary initializer can't be (no extension indexer in C# yet).Dictionary initializer maybe subjectively slightly more readable when it comes to initializing a dictionary :)
Dictionary initializer is C# 6.0 feature whereas collection initializer is available from C# 3.0 onwards.