Monday 11 November 2013

C#.NET - Object and Collection Initializers


Object and Collection Initializers are introduced in C# 3.0. These are very convenient fast and most readable. 

Observe the following Employee Class

public class Employee
{
    public string Name { get; set; }
    public string Designation { get; set; }
    public int Salary { get; set; }
}

Object Initializers

---------------------------
We can assign values to accessible fields and properties of an object at the time of object creation without having to explicitly invoking a constructor.

Creating an Employee type object

Employee emp1 = new Employee();
emp1.Name = "Srinu";
emp1.Designation = "Software Engineer";
emp1.Salary = 20000;
By using the Object initialisers we can create the same object in a single expression as follows. It is very simple and most readable.
Employee emp1 = new Employee()
{
    Name = "Srinu",
    Designation = "Software Engineer",
    Salary = 20000
};

Collection Initializers

--------------------------------
Collection Initializers are similar to the Object initializers.

Generally we will add the objects to the collection by using the Add method.
List<Employee> employees = new List<Employee>();

employees.Add(new Employee() { Name = "Srinu", Designation = "Software Engineer", Salary = 20000 });
employees.Add(new Employee() { Name = "Ramakee", Designation = "Sr. Software Engineer", Salary = 30000 });
employees.Add(new Employee() { Name = "Gajendra", Designation = "SEO", Salary = 10000 });
But collection initializers add objects to the collection directly at the time of creation of Collection.
List<Employee> employees = new List<Employee>()
        {
            new Employee() {Name = "Srinu", Designation = "Software Engineer", Salary = 20000},
            new Employee() {Name = "Ramakee", Designation = "Sr. Software Engineer", Salary = 30000},
            new Employee() {Name = "Gajendra", Designation = "SEO", Salary = 10000}
        };
Note:
To be able to use a Collection Initializer on an object, the object must satisfy these two requirements:
1. It must implement IEnumarable Interface.
2. Must have public Add() method.

No comments: