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 = newstring []

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

//Dictionary object initialization

Dictionary<int , string> objDic =

newDictionary<int , string>

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

//Generic Initialization

List<Cust> objCusts = newList<Cust>{

newCust {ID=1, Name= "Wriju" },

newCust {ID=2, Name= "Writam" },

newCust {ID=3, Name= "Deb" },

newCust {ID=4, Name= "Sumitra" }};

Namoskar!!!