Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata