Welcome to MSDN Blogs Sign in | Join | Help

Wriju's BLOG

.NET and everything
C# 3.0 Enhancements: Collection Initializers

In C# 3.0 we can easily initialize collection. It is smarter and concise way of writing code.

 

There are couple of things we should consider while initializing the collection.

Ø       The collection should implement ICollection<T>

Ø       The collection should have a provision to invoke ICollection<T>.Add(T)

 

 

Here is couple of them. I am sure that you are very excited.

 

//Array of string initialization

string[] sTest = new string[]

{ "Wriju", "Writam", "Deb", "Sumitra" };

 

//Dictionary object initialization

Dictionary<int, string> objDic =

new Dictionary<int, string>

{ { 0, "Zero" }, { 1, "One" } };

 

//Generic Initialization

List<Cust> objCusts = new List<Cust>{

new Cust{ID=1, Name="Wriju"},

     new Cust{ID=2, Name="Writam"},

     new Cust{ID=3, Name="Deb"},

     new Cust{ID=4, Name="Sumitra"}};

 

Namoskar!!!

Posted: Friday, April 13, 2007 11:02 PM by wriju
Filed under: , , ,

Comments

Insert Catchy Title Here said:

A Better Dictionary Initializer

# December 29, 2007 9:38 AM

And in VB.NET? said:

Yeah, so when is the Visual Basic team gonna get it together and make these?

# January 24, 2008 3:47 PM

wriju said:

In VB you have array Initializer.

# January 24, 2008 4:26 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker