What is a collection initializer?

Collection initializer is a new featured added to C# 3.0. Let's take a look at this sample code:

List<string> names = new List<string>();

names.Add("Mahesh Chand");

names.Add("Mike Gold");

names.Add("Matt Chochran");

names.Add("Praveen Kumar");

 

var selectedNames = from name in names

                    select name;

foreach(var n in selectedNames)

    Console.WriteLine(n);

Console.ReadLine();

 

In the above code, we create a collection called list of strings (List<string>) and add items to this collection by calling the Add method.

Now using this new feature, we can initialize this collection when we create the collection as following:

List<string> names = new List<string>()

    { "Mahesh Chand", "Mike Gold", "Matt Chochran", "Praveen Kumar" };

//names.Add("Mahesh Chand");

//names.Add("Mike Gold");

//names.Add("Matt Chochran");

//names.Add("Praveen Kumar");

 

var selectedNames = from name in names

                    select name;

foreach(var n in selectedNames)

    Console.WriteLine(n);

Console.ReadLine();

 

 

Next Recommended Reading Get am/pm from datetime in sql query