TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

Collection Initializers C# 3.0

Collection Initializers enables 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.

Collection Initializers enables 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.

Here above each Employeeobject 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)}
};

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading