Creating Strongly Typed Custom Collections in C#


First, I want to thank the group of the VS .NET for their great achievements in the world of programming. I saw that with this new technology we can implement everything we could implement with VC++, VB, .. etc, and in a very simple manner.

Second, I liked the idea of the collections very much. Using the .NET, we can easily create and manipulate collections, even easier than working with it in the MFC. It's also possible to implement strongly typed collections, and this is what I shall talk about.

The .NET has provided a way of working with specific collections such as string collections, int collections, ...etc, but what if the programmer tried to make a collection of his own type of objects?!! The answer is that he has to create a class that is derived from CollectionBase and provide the type of the items of the collection he wants.

The CollectionBase class is derived directly from the System.Object class, and it implements three interfaces: IList, ICollection and IEnumerable, and in order to fully implement your strongly typed collection class, you have to implement IList.Add, IList.Insert, IList.Remove, IList.Contains, IList.IndexOf and ICollection.CopyTo(). Also you should implement the indexer of your collection class so as to make it return your specific type. Here is an example:

class MyItem
{
private m_strMyItemName;
public string MyItemName
{
get { return m_strMyItemName; }
set { m_strMyItemName = value; }
}
public MyItem()
{
}
public MyItem(string strItemName)
{
m_strMyItemName = strItemName;
}
}
class MyItemCollection : CollectionBase
{
public int Add(MyItem item)
{
return List.Add(item);
}
public void Insert(int index, MyItem item)
{
List.Add(index, item);
}
public void Remove(MyItem item)
{
List.Remove(item);
}
public bool Contains(MyItem item)
{
return List.Contains(item);
}
public int IndexOf(MyItem item)
{
return List.IndexOf(item);
}
public void CopyTo(MyItem[] array, int index)
{
List.CopyTo(array, index);
}
public MyItem this[int index]
{
get { return (MyItem)List[index]; }
set { List[index] = value; }
}
}

Note that it is too easy to implement strongly typed collections; all you have to do is to implement the mentioned methods. Now, after you have created your own collection class, you are also able to add your own methods to the collection so as to ease working with it. For example, I can add an Add method that accepts a string containing the name of the MyItem object that will be added instead of adding an MyItem object:

public int Add(string strItemName)
{
MyItem item =
new MyItem(strItemName);
return List.Add(strItemName);
}

Now, I have my own method, called Add(string strItemName), that I may use instead of creating a new instance of MyItem, specify its name by myself and then call the Add(MyItem item) method.

Up Next
    Ebook Download
    View all
    Learn
    View all