27 Oct 2016 @ 12:39 PM 

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:

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:

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:

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!

Posted By: BC_Programming
Last Edit: 27 Oct 2016 @ 12:40 PM

EmailPermalink
Tags
Tags: , ,
Categories: .NET, C#, Programming


 

Responses to this post » (None)

 
Post a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Tags
Comment Meta:
RSS Feed for comments

 Last 50 Posts
 Back
Change Theme...
  • Users » 41921
  • Posts/Pages » 350
  • Comments » 104
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

PP



    No Child Pages.

Windows optimization tips



    No Child Pages.

BC’s Todo List



    No Child Pages.