Section 10.2. Type Parameters


10.2. 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 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) 




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net