Monday, December 10, 2007

C# 3.0 Collection Initializers

C# 3.0 has a nice feature of creating collection of objects in a simple way like C# 3.0 object initializers.

Class Structure:

class Customer
{

#region Automatic Properties

public long CustomerID
{
get;
set;
}

public string Name
{
get;
set;
}

#endregion

}


Conventional Method:

// C# 3.0 object Initialization Method
Customer custmObj1 = new Customer { CustomerID = 1, Name = "Ayyanar" };
Customer custmObj2 = new Customer { CustomerID = 2, Name = "Senthil" };
Customer custmObj3 = new Customer { CustomerID = 3, Name = "Vaithy" };

//List of Customer

List<Customer> listCust = new List<Customer>();

// Adding the object into the Customer List
listCust.Add(custmObj1);
listCust.Add(custmObj2);
listCust.Add(custmObj3);



C# 3.0 :


List<Customer> listStr = new List<Customer> {
new Customer{CustomerID = 1, Name = "Ayyanar"},
new Customer{CustomerID = 2, Name = "Senthil"},
new Customer{CustomerID = 3, Name = "Vaithy"},
};





In single statement, we can populate the multiple object into the list.

No comments: