C# Collection Initializers enable you to add items in the collection at the time of instantiation of the collection. Collection can be a List or Dictionary or any other available C# collection.
Till C# 2.0, for creating a collection of Employees we normally do
List<Employee> employees = new List<Employee>(); employee.Add(new Employee("EMP001","Sam","Bangalore,India",20000)); employee.Add(new Emploee("EMP00","Peter","Bombay,India",30000)); employee.Add(new Emploee("EMP003","Tom","Delhi,India",40000));
Assuming that there is an overloaded constructor for the Employee class.
Here above, each Employee object is added one by one after creating the collection instance.
In C# 3.0 by the use of collection Initializers, it is possible to declare and initialize the collection in line directly as below.
List<Employee> employees = new List<Employee>() { new Employee("EMP001","Sam","Bangalore,India",20000), new Emploee("EMP002","Peter","Bombay,India",30000) new Emploee("EMP003","Tom","Delhi,India",40000) };
Similarly, any other collection can be declared. See a dictionary example below
Dictionary<string,Employee> employeeDictionary = new Dictionary<string,Employee>() { {"Emp1",new Employee("EMP001","Sam","Bangalore,India",20000)}, {"Emp2",new Employee("EMP002","Tom","Delhi,India",40000)} };
Leave a Reply