Collection Initializers in C# 3.0

No.of Views492
Bookmarked0 times
Downloads 
Votes0
By  ayyanarj   On  07 May 2010 21:05:16
Tag : CSharp , How to
How to initial collection in Csharp 3.0 with .NET framework 3.0 or later version.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

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

Code Sample

 

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"},
};

See how its easier and less lines of code.

 
Sign Up to vote for this article
 
About Author
 
ayyanarj
Occupation-Software Engineer
Company-Effindi Technologies Private Limited
Member Type-Junior
Location-India
Joined date-04 Aug 2009
Home Page-http://ayyanar.blogspot.com
Blog Page-http://ayyanar.blogspot.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top