C# 6.0–Dictionary Initializers

  • Home
  • Blog
  • 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 Person = new Dictionary()
            {
                [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.

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