#837 – Object Initializers within Collection Initializers

Recall that you can initialize a collection when it is declared, using a collection initializer.

            List<Dog> myDogs = new List<Dog>
            {
                new Dog("Kirby", 15),
                new Dog("Ruby", 3)
            };

Also recall that, instead of invoking a constructor, you can initialize an object by using an object initializer.

            Dog myDog = new Dog { Name = "Kirby", Age = 15 };

You can combine these techniques, using object initializers within collection initializers.

            List<Dog> myDogs = new List<Dog>
            {
                new Dog { Name = "Kirby", Age = 15 },
                new Dog { Name = "Ruby", Age = 3 }
            };
Advertisement

#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)
            };

836-001

#835 – A Generic List Can Store Value-Typed or Reference-Typed Objects

You can use a generic list, defined by the List<T> class, to store a dynamically sized collection of objects.  A List<T> can store any type of object, including both value-typed and referenced-typed objects.

            // List of integers
            List<int> favNumbers = new List<int>();
            favNumbers.Add(5);
            favNumbers.Add(49);

            // List of Dog objects
            List<Dog> myDogs = new List<Dog>();
            myDogs.Add(new Dog("Kirby", 15));
            myDogs.Add(new Dog("Ruby", 3));

            // List of structs
            List<Point3D> points = new List<Point3D>();
            points.Add(new Point3D(1.0, 1.0, 0.5, "Here"));
            points.Add(new Point3D(2.0, 2.0, 0.5, "There"));

835-001