Logo 
Search:

C# Articles

Submit Article
Home » Articles » C# » Programming BasicsRSS Feeds

Collection initializer

Posted By: Alfonsa Miller     Category: C#     Views: 5829

Article explaining collection initializer in .Net Framework, with practical programing example

1. Collection initializer is new feature of C# 3.0
2. Collection initializer gives a simple syntax to create instance of a collection.
3. Any object that is implementing System.Collections.Generic.ICollection<T> can
be initialized with collection initializer.

Let us say, we have a class

Person.cs
public class Person
{
      public string FirstName { get; set; }
      public string LastName { get; set; }
}

Now if we want to make collection of this class and add items of type student in that collection and
retrieve through the collection, we need to write below code

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication16
{
	class Program
	{
		static void Main(string[] args)
		{
			List lstPerson = new List();
			Person person1= new Person();
			person1.FirstName = "David";
			person1.LastName = "Peterson";
			lstPerson .Add(person1);

			Person person2= new Person();
			person2.FirstName = "Julie ";
			person2.LastName = "Smith";
			lstPerson .Add(person2);
			
			foreach (Person person in lstPerson)
			{
				Console.WriteLine(person.FirstName + " " + person.LastName);
			}
			Console.Read();
		}
	}
}
Output
David Peterson
Julie Smith

Lets understand how above code is working.
1. An instance of List of Person is getting created.
2. An instance of the Person is getting created.
3. Using the Add method on the list, instance of being added to list of Person .
4. Using For each statement iterating through the list to get the values.

Now, if instance of Person class can be assigned to List of Person at the time of creation of instance of
list then we call it automatic collection initializer.
List lstPerson = new List()
{
	new Person{FirstName="David", LastName="Peterson"},
	new Person{FirstName="Julie", LastName="Smith"},
};
  
Share: 

 
 
 

Didn't find what you were looking for? Find more on Collection initializer Or get search suggestion and latest updates.

Alfonsa Miller
Alfonsa Miller author of Collection initializer is from Frankfurt, Germany.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!