DELEGATES

A delegate is a type that refers to a subroutine, function, or other method. The method can be an instance method provided by an object, a class’s shared method, or a method defined in a code module. A delegate variable acts as a pointer to a subroutine or function. Delegate variables are sometimes called type-safe function pointers.

The Delegate keyword defines a delegate type and specifies the parameters and return type of the method to which the delegate will refer.

The following code demonstrates a delegate:

' Define a StringDisplayerType delegate to be a pointer to a subroutine
' that has a string parameter.
Private Delegate Sub StringDisplayerType(ByVal str As String)
 
' Declare a StringDisplayerType variable.
Dim DisplayStringRoutine As StringDisplayerType
 
' Assign the variable to a subroutine.
DisplayStringRoutine = AddressOf ShowStringInOutputWindow
 
' Invoke the delegate's subroutine.
DisplayStringRoutine("Hello world")

The code uses a Delegate statement to declare the StringDisplayerType to be a reference to a subroutine that takes a string as a parameter. Next, the code declares the variable DisplayStringRoutine to be of this type. This variable can hold a reference to a subroutine that takes a string parameter. The code then sets the variable equal to the ShowStringInOutputWindow subroutine. Finally, the code invokes the delegate’s subroutine, passing it a string.

The delegate in the preceding example holds a reference to a subroutine defined in a code module. ...

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.