21.7 C# 6 Dictionary Initializers and Collection Initializers

C# 6 supports two new features with respect to initializing collections—index initializers and using collection initializers with collections that have an Add extension method.

C# 6 Index Initializers

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
};

C# 6 Collection Initializers Now Support Collections with Add Extension Methods

Prior 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset