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

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.