kunal-chowdhury.com

What’s new in C# 6.0? - Dictionary Initializer


Visual Studio 2015 and .NET 4.6 came up with another new feature (more precisely an enhancement) for C# 6.0 named “Dictionary Initializer”. It’s not a new thing but now you will be able to map the key/indexer directly at the time of dictionary object initialization.

 

Today in this blog post, we will discuss about this with an example. Don’t forget to read the other new features which I posted earlier. Links can be found in this post.

 

 

Don’t forget to read my previous posts on this series:

 

Dictionary Initialization is not a new thing in C#. It was present since C# 3.0, but in C# 6.0 Microsoft enhanced this by adding a new ability to use the key/indexer to map with the dictionary values directly during the initialization itself.

 

The following code snippet shows how dictionary initializer were used prior to C# 6.0 to initialize dictionary objects with key and values. This is still valid and you can use as earlier.

 

Whats new in CSharp 6.0 - Dictionary Initialization (old ways)

In C# 6.0, the dictionary initialization happens same way but with keys as indexers which makes the code easy to read and understandable. Here is a piece of code to show you how the new initializing feature can be used. This is almost similar to how you access them e.g. errorCodes [1] = “Ex000001”.

 

Whats new in CSharp 6.0 - Dictionary Initialization (new way)

How much did you like this new feature/enhancement in C# 6.0 and how much will you use it in coming projects when you start using C# 6.0? Do let us know in the below comment section. Don’t forget to read the other posts on the same topic “What’s new in C# 6.0?”

 

Subscribe to my blog’s RSS feed and Email Newsletter to get the immediate updates directly delivered to your inbox. I am available on Twitter, Facebook, Google+ and LinkedIn. Do connect with me there and get the updates that I share over those social networking sites.

 


Kunal Chowdhury
If you have come this far, it means that you liked what you are reading (What’s new in C# 6.0? - Dictionary Initializer).

Why not reach little more and connect with me directly on Twitter, Facebook, Google+ and LinkedIn. I would love to hear your thoughts and opinions.

Authored Books: