C# 6.0 Features Series
- How to try C# 6.0 and Rosyln?
- Getter-only (Read Only) Auto Properties in C# 6.0
- Lambda and Getter Only Auto-Properties in C# 6.0
- Initializers for Read-Only Auto Properties in C# 6.0
- Initializers via Expression Auto Properties in C# 6.0
- C# 6.0 – A field initializer cannot reference the non-static field, method, or property
- Lambda Expression for Function Members in C# 6.0
- Dictionary Initializers (Index Initializers) in C# 6.0
- Expression Bodies on Methods returning void in C# 6.0
- using keyword for static class in C# 6.0
- Unused namespaces in Different Color in Visual Studio 2015
- Null-Conditional Operator in C# 6.0
- Null-Conditional Operator and Delegates
- nameof Operator in C# 6.0
- Contextual Keywords in C#
- String Interpolation in C# 6.0
- Exception Filters in C# 6.0
- Await in Catch and finally block in C# 6.0
The Object Initializer is one of the useful feature that lets the developers to initialize properties of the objects or collections when declaring them.
With the earlier version of C# 6.0 , initializing the dictionary entries with collection initializer was less elegant. It included adding many flower brackets as shown below.
Dictionary<string, Employee> Developers = new Dictionary<string, Employee> { { "Senthil" , new Employee { FirstName = "Senthil", LastName = "Kumar" } }, { "Norton", new Employee { FirstName = "Norton", LastName = "Stanley" }}, { "Rupam", new Employee { FirstName = "Rupam", LastName = "Khaitan" }}, { "F5Debug", new Employee { FirstName = "Karthikeyan", LastName = "Anbarasan" } }, { "Ashok", new Employee { FirstName = "Ashok", LastName = "Kumar" }}, };
Dictionary Initializers (Index Initializers) in C# 6.0
The new syntax in C# 6.0 allows the developers to set values through indexer which the new object contains as shown below.
Dictionary<string, Employee> Developers1 = new Dictionary<string, Employee> { ["Senthil"] = new Employee { FirstName = "Senthil", LastName = "Kumar" }, ["Norton"] = new Employee { FirstName = "Norton", LastName = "Stanley" }, ["Rupam"] = new Employee { FirstName = "Rupam", LastName = "Khaitan" }, ["Karthikeyan"] = new Employee { FirstName = "Karthikeyan", LastName = "Anbarasan" }, ["Ashok"] = new Employee { FirstName = "Ashok", LastName = "Kumar" }, };
When we look at the code generated using the decompiled tool , you will notice that by default, the collection initializer uses the “Add” method of the Dictionary where as the new Dictionary Initializer uses the Indexer as shown in the below screenshot.