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<int, string> dic = new Dictionary<int, string>
  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<int, string> dic = new Dictionary<int, string>
  2. {
  3. [1] = "User C",
  4. [2] = "User B",
  5. [3] = "User C",
  6. };
  7. foreach (var item in dic)
  8. {
  9. Console.WriteLine($"Key is {item.Key} and Value is: {item.Value}");
  10. }
Run the code and see the results.


Happy coding.