Wriju's BLOG

.NET, Cloud 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”}};