Collection Initializers in .NET

Many of you have used property initializers in your code. Object initializers and property initializers are common operations of every program. But do you know, .NET supports Collection initilization directly for all IEnumerable objects ? In this post lets take a brief introduction of Collection Initializers in .NET.

Suppose you want to create an array which holds some values, you might write :

string[] myarray = {"Abhishek", "Abhijit", "Atul", "Jaberson" };

Oh, it works. myarray is going to initialize with values specified inside the curl braces.

You might think, this is very common syntax that we all know from basic programming languages. But yet, C# puts this further, lets demonstrate :

List mylst = {1,2,3,4,5};

Yes even this works as well. Actually curl braces produces an IEnumerable which you can cast to any custom collection type.

You can even use this syntax to do like this :

List mylst = { 1, 2, x * 20, this.GetInt(), 44 };

The 3rd value will be x times 20 and this.GetInt will be called for 4th value.
Hence it is nice to have feature for C#.
I hope this would help you.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434

One Comment to “Collection Initializers in .NET”

Comments are closed.