Collection Initializers in .NET - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

Saturday, May 28, 2011

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.

No comments:

Post a Comment