
Type Parameters | 135
Generics
This is the Title of the Book, eMatter Edition
Copyright © 2006 O’Reilly & Associates, Inc. All rights reserved.
the standard Stack class methods. This is a little better, since you wouldn’t
have to recode the entire Stack logic. But you would still have to do it again
for
String data. And all of this wrapping and type-casting between System.
Object and
Integer can’t be that efficient.
• Just use the existing Stack class and hope that only integers are used. Unfor-
tunately, this doesn’t really solve the problem.
Generics solve this problem by allowing an instance of a class to look like it was
written just for a restricted data type. All enforcement occurs at compile time, so
the program is also more efficient, since the data does not have to be converted to
System.Object and back again all the time. Visual Studio also uses the generic defi-
nitions to enhance the IntelliSense available when working with generics-enabled
types.
Generics are similar to a feature called templates in the C++ language, although
generics are somewhat easier to use and do not support all of the features avail-
able with templates.
Type Parameters
Consider the following subset of the Stack class definition.
Public Class StackSubset
Public Sub Push(ByVal obj As System.Object)
End Sub
End Class
To define this same class using generics, use the new Of keyword.
Public Class StackSubset(Of T)
Public ...