TechBubbles Microsoft Technology BLOG

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.                    

About the author

Kalyan Bandarupalli

My name is kalyan, I am a software architect and builds the applications using Microsoft .NET technologies. Here I am trying to share what I feel and what I think with whoever comes along wandering to Internet home of mine.I hope that this page and its contents will speak for me and that is the reason I am not going to say anything specially about my self here.

2 Comments

TechBubbles Microsoft Technology BLOG

Follow me

Archives

Tag Cloud