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:
- Dictionary<string, int> student = new Dictionary<string, int>();
-
- student.Add("Ravi Sharma", 20);
- student.Add("Mohit Sharma", 22);
- student.Add("Varun Sharma", 21);
-
- foreach(KeyValuePair<string,int> stu in student)
- {
- Console.WriteLine("Name : {0}, Age : {1}",stu.Key,stu.Value);
- }
- Initializing a Dictionary in C# 5.0.
Example:
- Dictionary<string, string> employee = new Dictionary<string, string>()
- {
- {"John","EMP101"},
- {"Rahul","EMP102"},
- {"Satish","EMP103"},
- {"Mohan","EMP104"},
- {"Ganesh","EMP105"}
- };
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:
-
- Hashtable Student = new Hashtable();
- Student.Add("Mohit Sharma",20);
- Student.Add("Varun Sharma",22);
-
-
- Dictionary<string, int> student1 = new Dictionary<string, int>();
- student1.Add("Mohit Sharma", 20);
- 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).
- Dictionary<string, string> employee = new Dictionary<string, string>()
- {
- ["John"]="EMP101",
- ["Rahul"]="EMP102",
- ["Satish"]="EMP103",
- ["Mohan"]="EMP104",
- ["Ganesh"]="EMP105"
-
- };
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).
- Dictionary<int, string> employee = new Dictionary<int, string>()
- {
- [25]="John",
- [28]="Rahul",
- [25]="Satish",
- [22]="Mohan",
- [26]="Ganesh"
-
- };
Example
If the keys data type is int and the values are a class type.
- class Employee
- {
-
- public string Name { get; set; }
- public string Email { get; set; }
-
- Employee empDetails = new Employee();
- empDetails.Email = "[email protected]";
- empDetails.Name = "JOHN";
-
- Dictionary<int, Employee> emp = new Dictionary<int, Employee>();
- emp.Add(1, empDetails);
- }
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.
- class Employee
- {
-
- static void Main(string[] args)
- {
- Dictionary<string, string> employee = new Dictionary<string, string>()
- {
-
- ["John"]="EMP101",
- ["Rahul"]="EMP102",
- ["Satish"]="EMP103",
- ["Mohan"]="EMP104",
- ["Ganesh"]="EMP105"
- };
-
- Console.WriteLine(@"Dictionary Initializers in C# 6.0\n\n
- List of all employees\n
- ------------------------");
-
- foreach (KeyValuePair<string, string> emp in employee)
- {
-
- Console.WriteLine("Name : \{emp.Key}\nEmpID : \{emp.Value}\n");
- }
- Console.ReadLine();
-
-
- }
- }
OUTPUT
Summary
In this article we saw the new way of Dictionary Initializers in C# 6.0 as well as the basics about Dictionary.