TechBubbles

Object and Collection Initializers Feature in C# 3.0

C# 3.0 introduced the another interesting feature Object and Collection initialization expressions.

Object Intialization  Expressions allows you to initialize an object without invoking the constructor and setting its properties.

If you take Employee Class as an Example:

public class Employee {
private int iEmpId;
private string strFirstName;
private string strLastName;

public int ID{
get{
return iEmpId;
}
}

public string FirstName {
get {
return strFirstName;
}
set {
strFirstName= value;
}
}

public string LastName {
get {
return strLastName;
}
set {
strLastName = value;
}
}

 public Employee() {}
}

We can use Object Intialization Expressions in C#3.0 Features  to create a Employee as follows:

Employee objEmployee  = new Employee {ID=007, FirstName = “Kalyan” LastName = “Bandarupalli” }

Now observe the above code we have neither  invoked the constructor nor set the any properties directly. The code above is equivalent to the following code:

 

Employee objEmployee = new Employee();

objEmployee.ID = 007;

objEmployee.FirstName = “Kalyan”;

objEmployee.LastName = “Bandarupalli”;

We can use Collection Intialization Expressions in C#3.0 Features  to create a list of Employees as follows:

 

List<Employee> listofEmployees  = new List<Employee>

{  {objEmployee.ID = 007,  objEmployee.FirstName = "Kalyan”},

     {objEmployee.ID = 007,  objEmployee.FirstName = "Suresh”},

    {objEmployee.ID = 007,  objEmployee.FirstName = "Naveen”}

  };

The advantage of using this feature is that it saves your time for creating a lot of constructors or initializing the individual property.                    

Related Posts:

2 comments

2 Comments so far

  1. Tech Bubbles » C# 3.0 features July 12th, 2008 7:57 am

    [...] 8. Object and Collection Intializers. [...]

  2. DotNetKicks.com July 14th, 2008 5:23 pm

    Object and Collection Initializers Feature in C# 3.0…

    You’ve been kicked (a good thing) – Trackback from DotNetKicks.com…

Leave a reply