Collection initializers let you specify one or more element intializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.
The following examples shows two simple collection initializers:
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<int> digits2 = new List<int> { 0 + 1, 12 % 3, MakeInt() }; The following collection initializer uses object initializers to initialize objects of the Cat class defined in an earlier example. Note that the individual object initializers are enclosed in braces and separated by commas.
List<Cat> cats = new List<Cat>
{
new Cat(){ Name="Sylvester", Age=8 },
new Cat(){ Name="Whiskers", Age=2},
new Cat() { Name="Sasha", Age=14}
};
You can specify null as an element in a collection initializer if the collection's Add method allows it.
List<Cat> moreCats = new List<Cat>
{
new Cat(){ Name="Furrytail", Age=5 },
new Cat(){ Name="Peaches", Age=4},
null
};