10.2. Type ParametersConsider 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 Sub Push(ByVal obj As T) End Sub End Class The T just after Of is a type parameter. (You can use another more descriptive name besides T.) This definition says, "In the StackSubset class, the type parameter T is acting kind of like a variable, but for data types. Anywhere it is used within the class, treat it as if it were just some normal type, like Integer or System.Windows.Forms.Form." An instance of the StackSubset class can now be created, specifying a specific data type for the T type parameter. Dim limitedStack As New StackSubSet(Of Integer) This statement creates an instance of the StackSubset class and will only allow Integer objects to be passed as arguments to the class's Push method. In addition to standard data types such as Integer, the Of clause can be used with any valid type, including interfaces, structures, and so on. If it can be treated as an instance of System.Object, you can use it to replace the T type parameter. Many of the collection classes available to .NET programmers have been modified in 2005 to support a generic type parameter. These new classes are located in the System.Collections.Generic namespace. The Stack class is one of the collections enabled for generics. Dim pileOfNumbers As New Stack(Of Integer) |