O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required