Collection initializer in C# 3.0

No.of Views899
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  05 Sep 2010 08:09:23
Tag : CSharp , Miscellaneous
In this article, i have demonstrate how to create collection initializer in C# 3.0
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

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

Student.cs

publicclass Student
    {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<Student> lstStudent = new List<Student>();
            Student std = new Student();
            std.FirstName = "Dhananjay";
            std.LastName = "Kumar "; 
            lstStudent.Add(std);
            std = new Student();
            std.FirstName = "Mritunjay ";
            std.LastName = "Kumar";
            lstStudent.Add(std);foreach (Student resstd in lstStudent)
            {
                Console.WriteLine(resstd.FirstName);
            }
            Console.Read();

          
        }
    }

 Output 

Image Loading

In above code,

1.    An instance of List of Student is getting created.
2.    An instance of the Student is getting created.
3.    Using the Add method on the list, instance of being added to list of students.
4.    Using For each statement iterating through the list to get the values.

Now, if instance of Student class can be assigned to List of student at the time of creation of instance of list then we call it automatic collection initializer. 

Image Loading

If we see the above syntax

1.    It is highly readable.
2.    It is single statement.
3.    Instance of Student class is getting added on the fly.

And we can retrieve the values as below, 

Image Loading

In retrieving implicit type local variable is being used to fetch the different instance of the student in list of student

List<Student> lstStudent = new List<Student>()
                                         {new Student{FirstName ="Dhananjay" ,LastName="Kumar"},new Student {FirstName ="Mritunjay", LastName ="Kumar"}
                                         };foreach (var r in lstStudent)
            {
                Console.WriteLine(r.FirstName);
            }

            Console.Read();

 Output

Image Loading

How it internally works?

A collection initializer invokes the ICollection<T>.Add(T) method for each specified element in order. In the above example , it will call

ICollection<Student>.Add(instance of Student )

hope helps to you, Thank you,

 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top