9.15. Creating a Strongly Typed Collection

Problem

You have some particular data type (and its descendent types) that you wish to store in a collection, and you do not want users of your collection to store any other data types within it.

Solution

Create a strongly typed collection by inheriting from the CollectionBase abstract base class. There are two ways to create a strongly typed collection; the first is to modify the parameters for all the overloaded methods to accept only a particular type. For example, instead of the Add method accepting a generic Object data type, you can change it to accept only one particular data type. A collection base that accepts only objects of a particular type (Media) or its descendents (Magnetic, Optical, or PunchCard) is shown here (note that the Media class and its descendents are defined in Recipe 3.4):

public class MediaCollection : CollectionBase
{
    public MediaCollection( ) : base( )
    {
    }

    public Media this[int index]  
    {
        get  
        {
            return ((Media)List[index]);
        }
        set  
        {
            List[index] = value;
        }
    }

    public int Add(Media item)  
    {
        return (List.Add(item));
    }

    public int IndexOf(Media item)  
    {
        return(List.IndexOf(item));
    }

    public void Insert(int index, Media item)  
    {
        List.Insert(index, item);
    }

    public void Remove(Media item)  
    {
        List.Remove(item);
    }

    public bool Contains(Media item)
    {
        return(List.Contains(item));
    }
}

The next method of writing a strongly typed collection involves the OnValidate event. This event is fired immediately before any action that modifies ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.