Dictionary
Initializers and Collection InitializersC# 6 supports two new features with respect to initializing collections—index initializers and using collection initializers with collections that have an Add
extension method.
Prior to C# 6, you could use a fully braced collection initializer to initialize a Dictionary
’s key–value pairs. For example, if you have a Dictionary<string, int>
named toolInven-tory
, you could create and initialize it as follows:
var toolInventory = new Dictionary<string, int>{
{"Hammer", 13},
{"Saw", 17},
{"Screwdriver", 7}
};
This is shorthand for creating the Dictionary
then using its Add
method to add each key– value pairs.
C# 6 introduces the index initializers, which enable you to clearly indicate the key and the value in each key–value pair as follows:
var toolInventory = new Dictionary<string, int>{
["Hammer"] = 13,
["Saw"] = 17,
["Screwdriver"] = 7
};
Add
Extension MethodsPrior to C# 6, any collection that defined an Add
instance method could be initialized with a collection initializer. As of C# 6, the compiler also supports collection initializers for any collection that has an Add
extension method.