Collection Initializers in .NET

By | March 25, 2011

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.

One thought on “Collection Initializers in .NET

  1. Pingback: Dew Drop – March 26, 2011 | Alvin Ashcraft's Morning Dew

Comments are closed.