Collection initializers (introduced in C# 3.0) provide an easy way to initialize a collection of items. For example, instead of doing this…
List<Color> colors = new List<Color>(); colors.Add(new Color { Value = 0xFFF0F8FF, Name = "Alice Blue" }); colors.Add(new Color { Value = 0xFF9400D3, Name = "Dark Violet" }); colors.Add(new Color { Value = 0xFF708090, Name = "Slate Gray" });
…we can do this:
List<Color> colors = new List<Color> { new Color { Value = 0xFFF0F8FF, Name = "Alice Blue" }, new Color { Value = 0xFF9400D3, Name = "Dark Violet" }, new Color { Value = 0xFF708090, Name = "Slate Gray" } };
But what if we want to initialize a dictionary? The traditional way would be like this:
Dictionary<UInt32, String> colors = new Dictionary<UInt32, String>(); colors.Add(0xFFF0F8FF, "Alice Blue"); colors.Add(0xFF9400D3, "Dark Violet"); colors.Add(0xFF708090, "Slate Gray");
But how would we use a collection initializer? When you iterate through a dictionary, each item is a KeyValuePair<TKey, TValue>. But we can’t do this:
Dictionary<UInt32, String> colors = new Dictionary<UInt32, String> { new KeyValuePair<UInt32, String>(0xFFF0F8FF, "Alice Blue"), new KeyValuePair<UInt32, String>(0xFF9400D3, "Dark Violet"), new KeyValuePair<UInt32, String>(0xFF708090, "Slate Gray") };
The solution is not entirely obvious, but it is succinct:
Dictionary<UInt32, String> colors = new Dictionary<UInt32, String> { { 0xFFF0F8FF, "Alice Blue" }, { 0xFF9400D3, "Dark Violet" }, { 0xFF708090, "Slate Gray" } };
This is not mentioned in the MSDN link shown above, but MSDN does discuss it here.
Hope this helps!
Advertisement