Dictionary Initialization In C#

This blog explains how can we initialize a Dictionary, as per a new feature in C# 6.0. Earlier, Dictionary of any type, say int, string can be initialized in the way given below.
  1. Dictionary<intstring> dic = new Dictionary<intstring>  
  2.          {  
  3.              { 1, "User A" },  
  4.              { 2, "User B" },  
  5.              { 3, "User C" },  
  6.          };  
In C# 6.0, another way of initialization was introduced with a slight change in the syntax. We can now directly create a key and assign a value to this key. Hence, as per the new technique, we can also have the code given below.
  1. Dictionary<intstring> dic = new Dictionary<intstring>  
  2.            {  
  3.                [1] = "User C",  
  4.                [2] = "User B",  
  5.                [3] = "User C",  
  6.            };  
  7.   
  8.            foreach (var item in dic)  
  9.            {  
  10.                Console.WriteLine($"Key is {item.Key} and Value is: {item.Value}");  
  11.            }  
Run the code and see the results.
 


Happy coding.