Collection initializer with example in C#.Net (c# 3.0 Feature)

This is new feature from c# 3.0. Using this we can create instance of the collection very easily.
.net interface is System.Collections.Generic.ICollection<T>

In the below example EmployeeList is the class. having eid and ename, in the page load we created list for the  EmployeeList.  After giving values to the class object, we have to add that object to the List. This scenario is also called as automatic collection initializer.
public partial class collectionInitializer : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        List<EmployeeList> lstEmployee = new List<EmployeeList>();
        EmployeeList objEmp = new EmployeeList();
        objEmp.eid = 1;
        objEmp.ename = "Ranga Rajesh Kumar";

        objEmp = new EmployeeList();
        objEmp.eid = 2;
        objEmp.ename = "Swapna";

        foreach (var data in lstEmployee)
            Response.Write(data.ename+"<br />");
public class EmployeeList
    public int eid;
    public string ename;

Ranga Rajesh Kumar

We can write above code in one line. like.

List<EmployeeList> lstEmployee = new List<EmployeeList>()
                                         new EmployeeList{eid="1",ename="Ranga  Rajesh Kumar"},
                                         new EmployeeList{eid="1",ename="Ranga  Rajesh Kumar"}

If you have any queries or suggestions, please feel free to ask in comments section.
Share this post :

Post a Comment

Please give your valuable feedback on this post. You can submit any ASP.NET article here. We will post that article in this website by your name.

Support : Ranga Rajesh Kumar
Copyright © 2012. ASP.NET Examples - All Rights Reserved
Site Designed by Ranga Rajesh Kumar