Wednesday, April 18, 2012

C# List


C# List

The List class in C# can be used to store typed objects. It is similar to an array but can store objects of custom type.

Arrays can hold objects of the predefined type like Integer, String, Boolean etc, but what if we need to store a list of objects belonging to a custom class which we define, this is where the List class comes into play, we can use the List to store custom objects of any type. Another advantage of the List over arrays is that we need not specify the dimension of the List while declaring, the List can dynamically grow/shrink as and when we add/remove items from the list.
The List can hold both the predefined types like Integer, String, Boolean, etc and custom types defined by us.

The List class comes under the System.Collections.Generic namespace, so make sure to include this namespace whenever you are using List.

using System.Collections.Generic;

Syntax
List<Type> lstObjects = new List<Type>();  

Example

First let us create a class clsCountry, later we shall store objects of this class in the List, here is our custom class.

public class clsCountry
{
    public string _CountryCode;
    public string _CountryName;
    //
    public clsCountry(string strCode, string strName)
    {
        this._CountryCode = strCode;
        this._CountryName = strName;
    }
    //
    public string CountryCode
    {
        get {return _CountryCode;}
        set {_CountryCode = value;}
    }
    //
    public string CountryName
    {
        get { return _CountryName; }
        set { _CountryName = value; }
    }
}

Now let us create a List to store a collection of objects of type clsCountry.
Here is the code.

List<clsCountry> lstCountry = new List<clsCountry>();
lstCountry.Add(new clsCountry("USA", "United States"));
lstCountry.Add(new clsCountry("UK", "United Kingdon"));
lstCountry.Add(new clsCountry("IND", "India"));
//
int nCount = lstCountry.Count();

Now objects of type clsCountry are added to the list lstCountry, the variable nCount will have a value of 3, since we added 3 objects to the List.

That’s it we have seen the advantages of using List with an Example.

Search Flipkart Products:
Flipkart.com

No comments: