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

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

Post a Comment

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

Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Creating PDF with ASP.Net MVC and RazorPDF

Solution: gulp is not recognized as internal or external command- Visual Studio