Thursday, January 8, 2015

C# 6.0–Dictionary Initializers

This blog post is part of C# 6.0 Features Series.
As we know c# 6.0 provides some cool new features and syntax sugar. Dictionary Initializers is one of them.  Till C# 5.0 we used to have collection initializers for collections but now C# 6.0 provides new way of initializing dictionary . This initialization features is available for there collections which supports index.

Following is a code for new way of initializing dictionary.
using System;
using System.Collections.Generic;

namespace DictionaryInitializer
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> Person = new Dictionary<int, string>()
            {
                [1] = "Jalpesh Vadgama",
                [2] = "Vishal Vadgama"
            };
            foreach (var person in Person)
            {
                Console.WriteLine("Key:{person.Key}, Value={person.Value} ");
            }
        }
    }
}

Here you see I have initialized dictionary in new way in square bracket I have putted key and after equal to sign I have putted values.  Isn’t that look beautiful and much more readable than older version of C# collection initializers.

Let’s run application and Following is a out put as expected.

dictionary-initializers-csharp6

That’s it. Hope you like it. Stay tuned fore more!

You can find all the example of  C# 6.0 new features on this blog  on github  at following location
https://github.com/dotnetjalps/Csharp6NewFeatures
Share:

2 comments:

  1. Needs to be updated with the new syntax.

    It is now

    catch (Exception ex) when (false)

    ReplyDelete
  2. Are you sure you needed the string.Format?

    ReplyDelete

Your feedback is very important to me. Please provide your feedback via putting comments.

Search This Blog
Loading...
About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews