#836 – Initializing a Generic List with an Object Initializer

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)