Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
18 Jan 2015 1  
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 it as earlier.

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

In C# 6.0, the dictionary initialization happens in the 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here