O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

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

Create a Strongly Typed Collection

Problem

You need to create a collection that can only contain one type of object and rejects attempts to add other data types.

Solution

Create a custom collection class by deriving from System.Collections.CollectionBase, and implement type-safe Add, Remove, and Item methods.

Discussion

You could create a custom collection by implementing the IList, ICollection, and IEnumerable interfaces. However, .NET provides an easier option with the abstract CollectionBase class. Internally, the CollectionBase uses an ArrayList, which is exposed through the protected property List.

As an example, consider the simple Customer object shown here:

Public Class Customer Private _ID As Integer Private _FirstName As String Private _LastName ...

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