Generic List

Generic List


  Here, in this post I will create an object of a class UserInfo to add it into List collection.
I will use Generic collection. I need to add below namespace in to my code.

using System.Collections.Generic;


Below is my UserInfo class.

public class UserInfo
{

    string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

    string _address;
    public string Address
    {
         get{return _address;}
         set{_address = value;}
    }
}


Now, I will create and populate 10 instances of UserInfo class using for loop.

  protected void Page_Load(object sender, EventArgs e)
    {
        List<UserInfo> lstUserInfo = new List<UserInfo>();

        for(int i =0; i<10; i++)
        {
            UserInfo u = new UserInfo();

            u.FirstName = "FirstName " +i;
            u.LastName = "LastName "+i;
            u.Address = "Address " + i;

            lstUserInfo.Add(u);

        }

        GridView1.DataSource = lstUserInfo;
        GridView1.DataBind();

    }


In above code, I have create new object inside for loop and added it into list (generic collection).

What if I don't create new instances of userInfo inside for loop? Check it out.

 protected void Page_Load(object sender, EventArgs e)
    {
        List<UserInfo> lstUserInfo = new List<UserInfo>(); 
        
       UserInfo u = new UserInfo();

        for(int i =0; i<10; i++)
        {

            u.FirstName = "FirstName " +i;
            u.LastName = "LastName "+i;
            u.Address = "Address " + i;

            lstUserInfo.Add(u);

        }

        GridView1.DataSource = lstUserInfo;
        GridView1.DataBind();

    }


If you run above code, you will notice each time the refrence of the userInfo is getting updated and we are putting same copy of UserInfo in generic List collection. As there is no new instance of UserInfo.

Satalaj

Tags:

c# arraylistLinq Inner JoinC# ArrayList Search using Linq Extension OfType MethodLinq Distinct ListGeneric ListListbox select multipleCheckbox Check all GridviewJquery Gridview Dropdownlist Selected Change Enable Disable Controlslistbox select eventC# Listbox ForeachListBox Asp.net Binding csharp

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.