Collection initializer let you specify one or more element initializer when you initialize a collection class.
The element initializer 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.
collection initializer is a series of comma-separated object initializers.
Example for Collection initializer in C#.NET
using System;
using System.Collections.Generic;
//Example for Collection Initializers in C#
namespace ProgramCall
{
class MainClass
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
static void Main(string[] args)
{
//Example 1
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//Example 2
List<Person> mylist = new List<Person>
{
new Person { Age=45, Name="John"},
new Person{Age =23, Name="Sam"},
new Person { Age=45, Name="Reddy"},
new Person{Age =23, Name="Peter"}
};
}
}
}