GENERIC METHODS

Generics are usually used to build classes that are not data type–specific such as the generic collection classes. You can also give a class (generic or otherwise) a generic method. Just as a generic class is not tied to a particular data type, the parameters of a generic method are not tied to a specific data type.

The method’s declaration includes an Of clause similar to the one used by generic classes, followed by the method’s parameter list.

Example program UseSwitcher uses the following code to define a generic Switch subroutine. This subroutine defines the generic type T and takes two parameters of type T. If this were a function, you could use the type T for its return value if you wanted. Subroutine Switch declares a variable temp of type T and uses it to switch the values of its parameters.

Public Class Switcher
    Public Sub Switch(Of T)(ByRef thing1 As T, ByRef thing2 As T)
        Dim temp As T = thing1
        thing1 = thing2
        thing2 = temp
    End Sub
End Class
 

The following code uses a Switcher object to switch the values of two Person variables. In the call to the Switch method, Visual Basic uses the first parameter to infer that the type T is Person and then requires the second parameter to have the same type.

Dim person1 As New Person("Anna")
Dim person2 As New Person("Bill")
Dim a_switcher As New Switcher()
a_switcher.Switch(person1, person2)
 

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.