CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Custom Collection in C# - Part 1

By Satheeshbabu
Posted On Feb 19,2008
Article Rating:
Be first to rate
this article.
No of Comments: 4
Category:
Print this article.

Custom Collection in C# - Part 1

A Strongly Typed Custom Collection with C#

 

In 1.x days we use ArrayList for creating Collection of objects. We can also create our own custom collection by inheriting the Arraylist or CollectionBase class. By creating our own collection which is strongly typed we can always prevent boxing and unboxing which has significant effect on the performance. The other reason for opting for our custom collection will be, we can have our application specific needs implemented in the collection like the one enumerating and sorting. With the introduction 2.0 which brought us the power of Generics, we can create our collection with generic List<T>, where T can be our BO, which is strongly typed. For example, List<Employee> will allow only Employee instance to be added to the list which is really cool! I will split this article into 2 parts, PART 1 deals with creating custom collection with CollectionBase class that have custom enumerations methods and PART 2 will discuss the implementation of generic custom collection with sorting methods.

 

CollectionBase class:

Before going to the actual implementation we will explore CollectionBase class. This is an Abstract class provided by the .netframework for implementing strongly typed custom collection. If we see the mscorlib assembly with reflector we can find this CollectionBase inside System.Collection namespace.

 

[Serializable, ComVisible(true)]

public abstract class CollectionBase : IList, ICollection, IEnumerable

{

    // Fields

    private ArrayList list;

 

    // Methods

    protected CollectionBase();

    protected CollectionBase(int capacity);

    public void Clear();

    public IEnumerator GetEnumerator();

    protected virtual void OnClear();

    protected virtual void OnClearComplete();

    protected virtual void OnInsert(int index, object value);

    protected virtual void OnInsertComplete(int index, object value);

    protected virtual void OnRemove(int index, object value);

    protected virtual void OnRemoveComplete(int index, object value);

    protected virtual void OnSet(int index, object oldValue, object newValue);

    protected virtual void OnSetComplete(int index, object oldValue, object newValue);

    protected virtual void OnValidate(object value);

    public void RemoveAt(int index);

    void ICollection.CopyTo(Array array, int index);

    int IList.Add(object value);

    bool IList.Contains(object value);

    int IList.IndexOf(object value);

    void IList.Insert(int index, object value);

    void IList.Remove(object value);

 

    // Properties

    [ComVisible(false)]

    public int Capacity { get; set; }

    public int Count { get; }

    protected ArrayList InnerList { get; }

    protected IList List { get; }

    bool ICollection.IsSynchronized { get; }

    object ICollection.SyncRoot { get; }

    bool IList.IsFixedSize { get; }

    bool IList.IsReadOnly { get; }

    object IList.this[int index] { get; set; }

}

 

This abstract class in turn inherits IList, ICollection, IEnumerable interfaces.

Below is the class diagram of the interfaces.

 

Consider the Employee BO,

 

public class Employee

{

       public Employee()

       {

              //

              // TODO: Add constructor logic here

              //

       }

    private int _Age;

    private string _Name;

 

    public int Age

    {

        get { return _Age; }

        set { _Age = value; }

    }

 

    public string Name

    {

        get { return _Name; }

        set { _Name = value; }

    }

 

}

 




The implementation of Employee custom collection will be,

 

public class EmployeeCollection : System.Collections.CollectionBase

{

       public EmployeeCollection()

       {

              //

              // TODO: Add constructor logic here

              //

       }

    public Employee this[int index]

    {

        get { return (Employee)this.List[index]; }

        set { this.List[index] = value; }

    }

 

    public int IndexOf(Employee item)

    {

        return base.List.IndexOf(item);

    }

 

    public int Add(Employee item)

    {

        return this.List.Add(item);

    }

 

    public void Remove(Employee item)

    {

        this.InnerList.Remove(item);

    }

 

    public void CopyTo(Array array, int index)

    {

        this.List.CopyTo(array, index);

    }

 

    public void AddRange(EmployeeCollection collection)

    {

        for (int i = 0; i < collection.Count; i++)

        {

            this.List.Add(collection[i]);

        }     

    }

 

    public void AddRange(Employee[] collection)

    {

        this.AddRange(collection);      

    }

 

    public bool Contains(Employee item)

    {

        return this.List.Contains(item);

    }

 

    public void Insert(int index, Employee item)

    {

        this.List.Insert(index, item);

    }

}

 

Now, we will add custom enumeration feature to iterate our custom collection. We will provide 2 enumeration, one will iterate into employees collection and return employees with age > 50 called SeniorEmployeeEnumerator and the other will return employees with age < 50 called JuniorEmployeeEnumerator.

 

public class SeniorEmployeeEnumerator : IEnumerable

{

    EmployeeCollection list = new EmployeeCollection();

 

    public SeniorEmployeeEnumerator(EmployeeCollection emplist)

    {

        list = emplist;

    }

 

    public IEnumerator GetEnumerator()

    {

        for (int i = 0; i < list.Count; i++)

        {

            if (list[i].Age > 50)

            {

                yield return list[i];

            }

        }

    }

    IEnumerator IEnumerable.GetEnumerator()

    {

        return (GetEnumerator());

    }

}

public class JuniorEmployeeEnumerator : IEnumerable

{

    EmployeeCollection list = new EmployeeCollection();

 

    public JuniorEmployeeEnumerator(EmployeeCollection emplist)

    {

        list = emplist;

    }

 

    public IEnumerator GetEnumerator()

    {

        for (int i = 0; i < list.Count; i++)

        {

            if (list[i].Age < 50)

            {

                yield return list[i];

            }

        }

    }

    IEnumerator IEnumerable.GetEnumerator()

    {

        return (GetEnumerator());

    }

}

 

So our EmployeeCollection will be like,

 

public class EmployeeCollection : System.Collections.CollectionBase

{

 

 

// CollectionBase, IList, ICollection member implementations

 

 

//Custom Enumerator

    public SeniorEmployeeEnumerator GetSeniorEmployeeEnumerator()

    {

        SeniorEmployeeEnumerator enume = new SeniorEmployeeEnumerator(this);

        return enume;

    }

    public JuniorEmployeeEnumerator GetJuniorEmployeeEnumerator()

    {

        JuniorEmployeeEnumerator enume = new JuniorEmployeeEnumerator(this);

        return enume;

    }

}

 

 

Usage:

Creating EmployeeCollection and binding to a grid,

        EmployeeCollection emplist = new EmployeeCollection();

      

        Employee  emp1 = new Employee ();

        emp1.Name = "Fatima";

        emp1.Age = 23;

        emplist.Add(emp1);

 

        Employee  emp2 = new Employee ();

        emp2.Name = "Evangeline";

        emp2.Age = 59;

        emplist.Add(emp2);

 

        Employee  emp3 = new Employee ();

        emp3.Name = "Damien";

        emp3.Age = 27;

        emplist.Add(emp3);

 

        Employee  emp4 = new Employee ();

        emp4.Name = "Cameroon";

        emp4.Age = 65;

        emplist.Add(emp4);

 

        Employee  emp5 = new Employee ();

        emp5.Name = "Babu";

        emp5.Age = 20;

        emplist.Add(emp5);

 

      

        GridView1.DataSource = emplist;

        GridView1.DataBind();

 

Using Custom Enumeration,

 

        Response.Write("<b>Junior Employee List</b><BR>");

        foreach (Employee em in emplist.GetJuniorEmployeeEnumerator())

        {

            Response.Write(em.Name);

        }

        Response.Write("<br>");

        Response.Write("<b>Senior Employee List</b><BR>");

        foreach (Employee em in emplist.GetSeniorEmployeeEnumerator())

        {

            Response.Write(em.Name);

        }

Download Source:

Download source
Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
collection classes
thanx useful article
check another link related to this topic
http://www.mindstick.com/Articles/62f1e1b7-4f54-4d29-8c59-aa08d1190db1/?Collection%20and%20Generic%20Collection%20Classes%20in%20C%20NET
Great Job
This is just the information I was looking for. Thanks for putting it out there.
Fantastic Article
This provided the answer to every question i had about how to create custom object collections and provided me with all the information i needed to complete my project.

THANK YOU!
excellent
good article. took most of the contents. thanks buddy.