Using collection initializers
suggest changeSome 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 a Dictionary<TKey, TValue>, nest each key and value in their own braces. That calls Add(key, value). It is not an anonymous type.
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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents