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.
[…] 8. Object and Collection Intializers. […]
Object and Collection Initializers Feature in C# 3.0…
You’ve been kicked (a good thing) – Trackback from DotNetKicks.com…