Chapter 30. Making Generic Classes

The section on collection classes in Lesson 16 explained how to use generic collection classes. For example, the following code defines a list that holds Employee objects:

Public Employees As New List(Of Employee)

This list can hold Employee objects only, and when you get an object out of the list, it has the Employee type instead of the less specific Object type.

Lesson 16 also described the main advantages of generic classes: code reuse and specific type checking. You can use the same generic List(Of ...) class to hold a list of Strings, Doubles, or Person objects. By requiring a specific data type, the class prevents you from accidentally adding an Employee object to a list of Order objects, and when you get an object from the list you know it is an Order.

In this lesson, you learn how to build your own generic classes so you can raise code reuse to a whole new level.

Note

Many other things can be generic. You can probably guess that you can build generic structures because structures are so similar to classes. You can also build generic methods (in either generic or nongeneric classes), interfaces, delegate types, and so on. This lesson focuses on generic classes.

DEFINING GENERIC CLASSES

A generic class declaration looks a lot like a normal class declaration with one or more generic type variables added in parentheses. For example, the following code shows the basic declaration for a generic TreeNode class:

Public Class TreeNode(Of T) ... End Class ...

Get Stephens' Visual Basic® Programming 24-Hour Trainer now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.