Search This Blog

Wednesday, January 19, 2011

Create Custom Genric List class

This article is about creating a custom List class. Suppose you want a List type called Employees which will hold employee class object in it. We can do it by defining a class of type generic List which is of type Employee.

Employee.cs

    public class Employee
    {
        int empId;
        string empName;
        string empDesig;

        public Employee()
        {
        }

        public Employee(int empId, string empName, string empDesig)
        {
            this.empId = empId;
            this.empName = empName;
            this.empDesig = empDesig;
        }

        public int EmpId
        {
            get { return empId; }
            set { empId = value; }
        }
        public string EmpName
        {
            get { return empName; }
            set { empName = value; }
        }
        public string EmpDesig
        {
            get { return empDesig; }
            set { empDesig = value; }
        }
    }


Now you can define your own Employee list type by inheriting Generic List<T> type which has type employee as parameter. Below is the code for the same.

Employees.cs

    public class Employees: List<Employee>
    {
        public MyList()
        {
        }

        public new void Add(Employee item)
        {
            base.Add(item);
        }

        public new IEnumerator<Employee> GetEnumerator()
        {
            return base.GetEnumerator();
        }

        public new Employee this[int index]
        {
            get { return this[index]; }
            set { this[index] = value; }
        }
    }

In the abouve example code function like Add, indexer are the basic implementation. You can have your own implementation.

No comments:

Post a Comment