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 set 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

  1. static void Main(string[] args)  
  2. {  
  3.     Dictionary<intstring> student = new Dictionary<intstring>();  
  4.     student.Add(1, "Student1");  
  5.     student.Add(2, "Student2");  
  6.     foreach (KeyValuePair<intstring> st in student)  
  7.     {  
  8.         Console.WriteLine("Roll No: {0} and Name: {1}", st.Key, st.Value);  
  9.     }  
  10.     Console.ReadKey();  
  11. }  
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.

  1. Dictionary<intstring> student = new Dictionary<intstring>();  

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

    1. Dictionary<intstring> student = new Dictionary<intstring>()  
    2. {  
    3.     {01,"Student1"},  
    4.     { 02,"Student2"},  
    5.     { 03,"Student3"},  
    6.     { 04,"Student4"},  
    7.     { 05,"Student5"}  
    8. }:  
  • In C# 6.0

    1. Dictionary<intstring> student = new Dictionary<intstring>()  
    2. {  
    3.     [01] = "Student1",  
    4.     [02] = "Student2",  
    5.     [03] = "Student3",  
    6.     [04] = "Student4",  
    7.     [05] = "Student5"  
    8. };   

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.
    1. Dictionary<intstring> student = new Dictionary<intstring>();  
    2. 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.
    1. Dictionary<intstring> student = new Dictionary<intstring>();  
    2. 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.

  1. foreach (KeyValuePair<intstring> st in student)  
  2.  {  
  3.      Console.WriteLine("Roll No: {0} and Name: {1}", st.Key, st.Value);  
  4.  }  
Demo Application using Visual Studio 2013

  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace CSharpFeatures  
  5. {  
  6.     class DictionaryInitializerVS13  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             Dictionary<stringstring> Book = new Dictionary<stringstring>  
  11.             {  
  12.                 { "A week with Gandhi","L. Fischer" },  
  13.                 {"Ghulam Giri","Jyotiba Phule" },  
  14.                 {"In an Antique Land","Amitabh Ghosh"},  
  15.                 {"My Experiments With Truth","M.K. Gandhi"}  
  16.             };  
  17.   
  18.             Dictionary<stringdouble> Contact = new Dictionary<stringdouble>  
  19.             {  
  20.                 {"Abhishek",1234567890 },  
  21.                 {"Shridhar",1102323615 },  
  22.                 {"Gaurav",3236646616 },  
  23.                 {"Mohit",2013245212 }  
  24.             };  
  25.   
  26.             Console.WriteLine("\n-- Book Dictionary --");  
  27.             foreach (KeyValuePair<stringstring> _book in Book)  
  28.             {  
  29.                 Console.WriteLine(" Book Name: {0}, Author Name: {1}\n", _book.Key, _book.Value);  
  30.             }  
  31.   
  32.             Console.WriteLine("\n-- Contact Dictionary --");  
  33.             foreach (KeyValuePair<stringdouble> _contact in Contact)  
  34.             {  
  35.                 Console.WriteLine(" Name: {0}, Contact: {1}\n", _contact.Key, _contact.Value);  
  36.             }  
  37.             Console.ReadKey();  
  38.         }  
  39.     }  
  40. }  

Output

VS13 Output

Demo Application using Visual Studio 2015 Preview

  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace CSharpFeatures  
  5. {  
  6.     class DictionaryInitializerVS15  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             Dictionary<stringstring> Book = new Dictionary<stringstring>  
  11.             {  
  12.                 ["A week with Gandhi"] = "L. Fischer",  
  13.                 ["Ghulam Giri"] = "Jyotiba Phule",  
  14.                 ["In an Antique Land"] = "Amitabh Ghosh",  
  15.                 ["My Experiments With Truth"] = "M.K. Gandhi"  
  16.             };  
  17.   
  18.             Dictionary<stringdouble> Contact = new Dictionary<stringdouble>  
  19.             {  
  20.                 ["Abhishek"] = 1234567890,  
  21.                 ["Shridhar"] = 1102323615,  
  22.                 ["Gaurav"] = 3236646616,  
  23.                 ["Mohit"] = 2013245212  
  24.             };  
  25.   
  26.             Console.WriteLine("\n-- Book Dictionary --");  
  27.             foreach (KeyValuePair<stringstring> _book in Book)  
  28.             {  
  29.                 Console.WriteLine(" Book Name: \{_book.Key}, Author Name: \{_book.Value}\n");  
  30.             }  
  31.   
  32.             Console.WriteLine("\n-- Contact Dictionary --");  
  33.             foreach (KeyValuePair<stringdouble> _contact in Contact)  
  34.             {  
  35.                 Console.WriteLine(" Name: \{_contact.Key}, Contact: \{_contact.Value}\n");  
  36.             }  
  37.             Console.ReadKey();  
  38.         }  
  39.     }  
  40. }  

Output

VS15 Output

Summary

In this article we learned about the new feature of C# 6.0, where we found some syntax change in dictionary initializers at the time of initialization that makes 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!


Similar Articles