Dictionary Initializers: A New Feature of C# 6.0

Introduction

On November 12, 2014, the day of the Visual Studio Connect() event, Microsoft announced Visual Studio 2015 Preview with many new and exciting features for developers for testing purposes. Microsoft announced the new version of C#, C# 6.0 that came with many improvements and new features. One of the newly introduced features of C# 6.0 is Dictionary Initializers.

Don't forget to read my previous posts on this series "A new feature of C# 6.0".

What is Dictionary Initializers?

A Dictionary<TKey, TValue> is a generic class that contains a collection of Key/Value pairs. In C# programming the dictionary can also be called an "associative array", "key-value pair", "index-value pair" and so on. The dictionary makes use of the Hash Table data structure to build up the key/value pair. The dictionary takes two parameters, one for the key and the other for the value. It acts like an advanced array system where we can define the index with any data type that sets up our data structure in a more meaningful way. Since a dictionary works with two parameters, both data types are to be defined when the dictionary is initialized. For using the dictionary in our application we need to add the "System.Collections.Generic" namespace.

Example

static void Main(string[] args)
{
    Dictionary<int, string> student = new Dictionary<int, string>();
    student.Add(1, "Student1");
    student.Add(2, "Student2");
    foreach (KeyValuePair<int, string> st in student)
    {
        Console.WriteLine("Roll No: {0} and Name: {1}", st.Key, st.Value);
    }
    Console.ReadKey();
}

Initialize A Dictionary Object In C#

As we know a dictionary takes two parameters, one for key and the other for value should be defined at the time of initialization. In the following code snippet, we will initialize a simple dictionary with an int and string as data types.

Dictionary<int, string> student = new Dictionary<int, string>();

We can also define some default initial values when the dictionary is initialized. The following code snippet will add a few data pairs in the object at the time of initialization.

  • In C# 5.0
    Dictionary<int, string> student = new Dictionary<int, string>()
    {
        {01, "Student1"},
        {02, "Student2"},
        {03, "Student3"},
        {04, "Student4"},
        {05, "Student5"}
    };
    
  • In C# 6.0
    Dictionary<int, string> student = new Dictionary<int, string>()
    {
        [01] = "Student1",
        [02] = "Student2",
        [03] = "Student3",
        [04] = "Student4",
        [05] = "Student5"
    };
    

Add/Remove Pairs In dictionary object

We can easily do insert and remove operations with a dictionary object.

  • For adding a new pair, we need to both the arguments (key and value) as a parameter in the Add method on the object.
    Dictionary<int, string> student = new Dictionary<int, string>();
    student.Add(1, "Student1"); // both key and value to add a new pair
    
  • For removing a pair, we need to only the key as a parameter in the Remove method on the object.
    Dictionary<int, string> student = new Dictionary<int, string>();
    student.Remove(1); // Only key to remove a pair
    

Traverse the pairs in a dictionary object

The "KeyValuePair" class can hold a single pair. When we perform traversing using a foreach loop then this class variable can be used to hold each pair and can process further if necessary.

foreach (KeyValuePair<int, string> st in student)
{
    Console.WriteLine("Roll No: {0} and Name: {1}", st.Key, st.Value);
}

Demo Application using Visual Studio 2013.

using System;
using System.Collections.Generic;
namespace CSharpFeatures
{
    class DictionaryInitializerVS13
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> Book = new Dictionary<string, string>
            {
                { "A week with Gandhi", "L. Fischer" },
                { "Ghulam Giri", "Jyotiba Phule" },
                { "In an Antique Land", "Amitabh Ghosh" },
                { "My Experiments With Truth", "M.K. Gandhi" }
            };
            Dictionary<string, double> Contact = new Dictionary<string, double>
            {
                { "Abhishek", 1234567890 },
                { "Shridhar", 1102323615 },
                { "Gaurav", 3236646616 },
                { "Mohit", 2013245212 }
            };
            Console.WriteLine("\n-- Book Dictionary --");
            foreach (KeyValuePair<string, string> _book in Book)
            {
                Console.WriteLine(" Book Name: {0}, Author Name: {1}\n", _book.Key, _book.Value);
            }
            Console.WriteLine("\n-- Contact Dictionary --");
            foreach (KeyValuePair<string, double> _contact in Contact)
            {
                Console.WriteLine(" Name: {0}, Contact: {1}\n", _contact.Key, _contact.Value);
            }
            Console.ReadKey();
        }
    }
}

Output

VS13 Output

Demo Application using Visual Studio 2015 Preview.

using System;
using System.Collections.Generic;
namespace CSharpFeatures
{
    class DictionaryInitializerVS15
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> Book = new Dictionary<string, string>
            {
                ["A week with Gandhi"] = "L. Fischer",
                ["Ghulam Giri"] = "Jyotiba Phule",
                ["In an Antique Land"] = "Amitabh Ghosh",
                ["My Experiments With Truth"] = "M.K. Gandhi"
            };
            Dictionary<string, double> Contact = new Dictionary<string, double>
            {
                ["Abhishek"] = 1234567890,
                ["Shridhar"] = 1102323615,
                ["Gaurav"] = 3236646616,
                ["Mohit"] = 2013245212
            };
            Console.WriteLine("\n-- Book Dictionary --");
            foreach (KeyValuePair<string, string> _book in Book)
            {
                Console.WriteLine(" Book Name: {_book.Key}, Author Name: {_book.Value}\n");
            }
            Console.WriteLine("\n-- Contact Dictionary --");
            foreach (KeyValuePair<string, double> _contact in Contact)
            {
                Console.WriteLine(" Name: {_contact.Key}, Contact: {_contact.Value}\n");
            }
            Console.ReadKey();
        }
    }
}

Output

Directory

Summary

In this article, we learned about the new feature of C# 6.0, where we found some syntax changes in dictionary initializers at the time of initialization that make the source code more cleaner. Don't forget to read my other articles on the series "A new feature of C# 6.0". Share your opinion about this feature and how will you use it in your project. Your comments are most welcome. Happy Coding!


Recommended Free Ebook
Similar Articles