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