O'Reilly logo

Visual Basic 2012 Programmer's Reference by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

DEFINING GENERICS

Visual Basic allows you to define generic classes, structures, interfaces, procedures, and delegates. The basic syntax for all of those is similar, so once you know how to make generic classes, making generic structures, interfaces, and the others is fairly easy.

To define a generic class, make a class declaration as usual. After the class name, add a parenthesis, the keyword Of, a placeholder for a data type, and a closing parenthesis. The data type placeholder is similar to a parameter name that you would give to a subroutine except it is a type, not a simple value. The class’s code can use the name ItemType to refer to the type associated with the instance of the generic class.

For example, suppose you want to build a binary tree that could hold any kind of data. The following code shows how you could define a BinaryNode class to hold the tree’s data:

Public Class BinaryNode(Of T)
    Public Value As T
    Public LeftChild As BinaryNode(Of T)
    Public RightChild As BinaryNode(Of T)
End Class
 

The class’s declaration takes a type parameter named T. (Many developers use the name T for the type parameter. If the class takes more than one type parameter separated by commas, they start each name with T as in TKey and TData.)

The class defines a public field named Data that has type T. This is where the node’s data is stored.

The class also defines two fields that refer to the node’s left and right children in the binary tree. Those fields hold references to objects from this ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required