Paul Kimmel demonstrates how to implement a strongly typed collection in C#. The strongly typed collection is a powerful and common pattern in .NET and offers a lot of benefit for the effort.
This article is adapted from Paul Kimmel's upcoming book, The Visual Basic .NET Developer's Book (Addison-Wesley, scheduled for publication Fall 2002, ISBN 0-672-32407-5).
The strongly typed collection is a common pattern in .NET. If you search the base class libraries representing the Common Language Infrastructure (CLI), popularly referred to as Rotor, you'll discover at least two dozen instances of strongly typed collections.
A strongly typed collection is a collection that contains a known type. You can inherit from the System.Collections.CollectionBase or System.Collections.ReadOnlyCollectionBase to implement a writable or read-only strongly typed collection. Similarly to an array, a strongly typed collection can be indexed like an array of a type, and a strongly typed collection and array (System.Array) implement IList and IEnumerable. Unlike an array, however, a strongly typed collection has an Add method that allows you to add objects, and manages growing the collection dynamically.
The following list describes the benefits of a strongly typed collection:
It can be used like an array of a specific object (as long as you implement an indexer, which we'll discuss in a moment).
It implements the IList, IListSource, and IEnumerable interfaces, which means that the strongly type collection can be bound to an object or enumerated.
It supports dynamic resizing automatically.
It supports serialization, because the base class has the Serializable attribute.
In short, a strongly typed collection has all of the benefits of a System.Array and a collection, without any of the headaches associated with either. As an added benefit, strongly typed collections are not very difficult to implement, as the rest of this article shows.