This lesson picks up from where we left off in the previous lesson, which showed us how to create Object Initializers and even showed how to add them to a List by passing them directly, as an input parameter, into the List’s Add() method. This lesson covers collection initializers, which allow you to create and initialize a generic collection into a valid state by adding instances of a given type to it.

Step 1: Understanding Collection Initializers via Object Initializers

Collection Initializers provide an even more elegant shorthand by allowing us to add each object to the List, right at the List’s instantiation. Note, once again, how you don’t have to include the identifier as the List holds reference to the object through its indexed position within the List:

cs-asp-048---collection-initializers.001

The code you see above removes much of the redundancy and some of the complexity of adding items to your collection. It works because, to the C# compiler, the entire code block up until the semicolon is considered one statement. So even though multiple actions are being taken, they are happening within the same declaration statement of the List<Car>.

Step 2: Understanding Initializer Benefits

Also, notice that we don’t have to reference the Car’s invocation parentheses for the empty constructor:

cs-asp-048---collection-initializers.002

Creating this kind of Collection Initializer may look strange, at first, but it is not much different from an Object Initializer. The List object is itself an object, like any other, that should be initialized to a valid state. Collection Initializers offer a convenient way to accomplish this.

Tip:

The main benefit we’re getting by embedding of the object initializer syntax inside of the collection initializer syntax – is that we’re putting the Collection into a valid state all in one shot. Otherwise, it’s possible to have an empty List which could serve the potential for errors.


Lessons in this Course