This is part of a series of posts covering new C# 6 features. Currently there are posts covering the following:
String Interpolation
Expression-bodied Members
Improved Overload resolution
The Null Conditional operator
Auto-Property Initializers
Yet another new feature introduced into C# 6 are a feature called Dictionary Initializers. These are another “syntax sugar” feature that shortens code and makes it more readable- or, arguably, less readable if you aren’t familiar with the feature.
Let’s say we have a Dictionary of countries, indexed by an abbreviation. We might create it like so:
1 2 3 4 5 6 |
Dictionary<String,Country> countries = new Dictionary<String, Country>() { {"CAN",new Country(Name:"Canada",Population:35160000,Area:9985000)}, {"USA",new Country(Name:"United States of America",Population:318900000,Area:9834000) }, {"MEX",new Country(Name:"Mexico",Population:122300000,Area:1973000) } }; |
This is the standard approach to initializing dictionaries as used in previous versions, at least, when you want to initialize them at compile time. C#6 adds “dictionary initializers” which attempt to simplify this:
1 2 3 4 5 6 |
Dictionary<String, Country> countries = new Dictionary<string, Country>() { ["CAN"] = new Country(Name:"Canada", Population:35160000, Area:9985000), ["USA"] = new Country(Name:"United States of America", Population:318900000, Area:9834000), ["MEX"] = new Country(Name:"Mexico", Population:122300000, Area:1973000) }; |
Here we see what is effectively a series of assignments to the standard this[] operator. It’s usually called a Dictionary Initializer, but realistically it can be used to initialize any class that has a indexed property like this. For example, it can be used to construct “sparse” lists which have many empty entries without a bunch of commas:
1 2 3 4 5 |
List<Country> countries = new List<Country>() { [0] = new Country(Name:"Canada", Population:35160000,Area:9985000), [300] = new Country(Name:"Sweden", Population:9593000,Area:450295) } |
The “Dictionary Initializer” which seems more aptly referred to as the Indexing initializer, is a very useful and delicious syntax sugar that can help make code easier to understand and read.
Have something to say about this post? Comment!