One line initialization of a Dictionary

The .NET 3.5 Framework not only brought us the Windows Communication & Presentation Foundation, it also contained an update of C# to version 3.0. With the celebrated lambda and var functionality.

One of the most useful features it introduced is/was one line initialization. A list of strings can be declared and initialized using the following line:

var list = new List<string>() { "String1", "String2", "String3" };

Luckily this feature is not limited to simple lists. A dictionary can be declared and initialized using the same approach:

var dictionary = new Dictionary<string, string>() { { "Key1", "Value1" }, { "Key2", "Value2" }, { "Key3", "Value3" } };

I have used this extensively with lists, but only recently discovered this was possible with dictionaries.

Tags:

One Response to “One line initialization of a Dictionary”

  1. Mariana says:

    Thanks for posting about this, I would love to read more about this topic.

Leave a Reply