Dictionary Initializers: A New Feature of C# 6.0

Overview

The new way to initialize a Dictionary is one of the new features of C# v6.0 announced by Microsoft at the Visual Studio Connect() event on November 12, 2014 in New York, USA. If you have missed the live announcement of this event, there is nothing to worry about it. If you want to watch the recording session of this event, click on #vsconnect.

Before proceeding to the explanation of the Dictionary Initializers in C# v6.0 let us see what a Dictionary is it and why we use it.

Definition:

A Dictionary is a generic class of C# that is used to represent a collection of keys and value pairs data. It takes two parameters, the first for keys and the second for values. As we know a Dictionary is a generic class so it takes the parameter as a generic type, it means we can use any type of parameter like int, string, float, class and so on. 

  • Adding data into a Dictionary collection

    Example:
    1. Dictionary<stringint> student = new Dictionary<stringint>();  
    2.   
    3. student.Add("Ravi Sharma", 20);  
    4. student.Add("Mohit Sharma", 22);  
    5. student.Add("Varun Sharma", 21);  
    6.   
    7. foreach(KeyValuePair<string,int> stu in student)  
    8. {  
    9.   Console.WriteLine("Name : {0}, Age : {1}",stu.Key,stu.Value);   
    10. }  
     
  • Initializing a Dictionary in C# 5.0.

    Example: 
    1. Dictionary<stringstring> employee = new Dictionary<stringstring>()  
    2. {  
    3.    {"John","EMP101"},  
    4.    {"Rahul","EMP102"},  
    5.    {"Satish","EMP103"},  
    6.    {"Mohan","EMP104"},  
    7.    {"Ganesh","EMP105"}  
    8. };  

  OldWay

Need of Dictionary

Basically a Dictionary is used whenever we need to keep the generic collection of data. As we know the same can be done with a HashTable that also takes the parameter in the keys and values pair but a huge difference between both of them. Let's see the similarities and differences between both of them.

  • Similarity:

    Both takes the parameters in key and value pairs

    Example:             
    1. //Using Hashtable  
    2. Hashtable Student = new Hashtable();  
    3. Student.Add("Mohit Sharma",20);   
    4. Student.Add("Varun Sharma",22);   
    5.   
    6. //Using Dictionary  
    7. Dictionary<stringint> student1 = new Dictionary<stringint>();  
    8. student1.Add("Mohit Sharma", 20);  
    9. student1.Add("Varun Sharma", 22);               
  • Differences:
     
    Dictionary HashTable
    If we are using Dictionary, we need to use System.Collections.Generic Namespace If we are using HashTable, we need to use System.Collections Namespace
    It is faster than HashTable It is slower than Dictionary because it requires boxing and unboxing
    It will generate error if we try to use a key that is not exist in the collection It will return null if we try to use a key that is not exist
    It is a generic type so we can use any type of data It's not a generic type

Let us see the new way to initialize Dictionary data. In the preceding discussions we saw the old way to initialize a Dictionary.

Dictionary Initializers In C# 6.0

In C# 6.0, the way to initialize a Dictionary object became simpler and looks more feasible than the way we previously initialized the older version of C#. Now we can put the key values in square brackets and put the value depending on the type of keys.

Example 

If the keys data type is string and the values are also strings. In this example we will use a Dictionary collection that will keep the employee's name (in a string ) and id (in a string also).  

  1. Dictionary<stringstring> employee = new Dictionary<stringstring>()   
  2. {  
  3.     ["John"]="EMP101",  
  4.     ["Rahul"]="EMP102",  
  5.     ["Satish"]="EMP103",  
  6.     ["Mohan"]="EMP104",  
  7.     ["Ganesh"]="EMP105" 
  8.   
  9. };  

Example

If the keys data type is int and the values are string. In this example we will use a Dictionary collection that will keep the employee's age (in an int ) and name (in a string). 

  1. Dictionary<intstring> employee = new Dictionary<intstring>()   
  2. {  
  3.     [25]="John",  
  4.     [28]="Rahul",  
  5.     [25]="Satish",  
  6.     [22]="Mohan",  
  7.     [26]="Ganesh"  
  8.   
  9. };  

Example

If the keys data type is int and the values are a class type.

  1. class Employee  
  2. {  
  3.   
  4.     public string Name { getset; }  
  5.     public string Email { getset; }  
  6.   
  7.     Employee empDetails = new Employee();  
  8.     empDetails.Email = "[email protected]";  
  9.     empDetails.Name = "JOHN";  
  10.   
  11.     Dictionary<int, Employee> emp = new Dictionary<int, Employee>();  
  12.     emp.Add(1, empDetails);  
  13. }  

 NewWayImage

Demo Application in C# 6.0

Now we will create a console application in C# 6.0 with the IDE Visual Studio 2015 Preview in which we will add some record to the Dictionary as well as use these collections to display the results of the application. 

  1. class Employee   
  2.  {  
  3.          
  4.         static void Main(string[] args)  
  5.         {  
  6.             Dictionary<stringstring> employee = new Dictionary<stringstring>()  
  7.             {  
  8.                 //New way to initialize Dictionary  
  9.                 ["John"]="EMP101",  
  10.                 ["Rahul"]="EMP102",  
  11.                 ["Satish"]="EMP103",  
  12.                 ["Mohan"]="EMP104",  
  13.                 ["Ganesh"]="EMP105"  
  14.             };  
  15.   
  16.             Console.WriteLine(@"Dictionary Initializers in C# 6.0\n\n  
  17.                                 List of all employees\n  
  18.                                 ------------------------");  
  19.   
  20.             foreach (KeyValuePair<stringstring> emp in employee)  
  21.             {                 
  22.                 // By using String Interpolation  
  23.                 Console.WriteLine("Name  : \{emp.Key}\nEmpID : \{emp.Value}\n");  
  24.             }  
  25.             Console.ReadLine();  
  26.   
  27.               
  28.         }          
  29.  }  

 OUTPUT

ImageOutput

Summary

In this article we saw the new way of Dictionary Initializers in C# 6.0 as well as the basics about Dictionary.

Up Next
    Ebook Download
    View all
    Learn
    View all