
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 List<Employee> Employees = new List<Employee>();
This list can only hold Employee objects, 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<> 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.
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 non-generic classes), generic inter-
faces, generic 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 angled brackets. For example, the ...