#836 – Initializing a Generic List with an Object Initializer
May 3, 2013 4 Comments
Instead of using the Add method repeatedly to populate a generic list, you can use an object initializer to initialize the contents of the list when you declare it.
The object initializer used to initialize a generic list consists of a set of braces, with a comma-separated list of elements within the braces. If the list’s type is a reference type, each element in the list is instantiated using the new operator.
This use of an object initializer, in initializing a collection, is known as a collection initializer.
// List of integers List<int> favNumbers = new List<int> { 5, 8, 42 }; // List of Dog objects List<Dog> myDogs = new List<Dog> { new Dog("Kirby", 15), new Dog("Ruby", 3) };
Pingback: Dew Drop – May 3, 2013 (#1,540) | Alvin Ashcraft's Morning Dew
Pingback: Interesting .NET Links - May 5 , 2013 | TechBlog
Pingback: The Daily Six Pack: May 6, 2013 | Dirk Strauss
Pingback: #1,133 – Initializing a Dictionary with a Collection Initializer | 2,000 Things You Should Know About C#