.NET Framework Collections Using collection initializers

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


Some collection types can be initialized at the declaration time. For example, the following statement creates and initializes the numbers with some integers:

List<int> numbers = new List<int>(){10, 9, 8, 7, 7, 6, 5, 10, 4, 3, 2, 1};

Internally, the C# compiler actually converts this initialization to a series of calls to the Add method. Consequently, you can use this syntax only for collections that actually support the Add method.

The Stack<T> and Queue<T> classes do not support it.

For complex collections such as the Dictionary<TKey, TValue> class, that take key/value pairs, you can specify each key/value pair as an anonymous type in the initializer list.

Dictionary<int, string> employee = new Dictionary<int, string>()
     {{44, "John"}, {45, "Bob"}, {47, "James"}, {48, "Franklin"}};

The first item in each pair is the key, and the second is the value.

Got any .NET Framework Question?