Title | Use a variable to hold delegates (function pointers) in Visual Basic 2005 |
Description | This example shows how to use a variable to hold delegates (function pointers) in Visual Basic 2005. |
Keywords | delegate, function pointer, function reference, method pointer, methd reference, Visual Basic 2005 |
Categories | Software Engineering, VB.NET |
|
|
A delegate is a variable that can hold a reference to a subroutine or function. This program uses a delegate variable to refer to each of three functions and then calls them.
Here are the three functions. Note that they have the same signature: all take an integer parameter and return an integer result.
|
|
Private Function A(ByVal x As Integer) As Integer
Return x + 1
End Function
Private Function B(ByVal x As Integer) As Integer
Return x * 2
End Function
Private Function C(ByVal x As Integer) As Integer
Return x * x
End Function
|
|
Here's the delegate type definition. Variables of this type can be assigned to any function that takes an integer parameter and returns an integer result.
|
|
Private Delegate Function ABCFunction(ByVal x As Integer) _
As Integer
|
|
Here's the variable declaration. The variable func can refer to a function that takes an integer parameter and returns an integer result.
|
|
Dim func As ABCFunction
|
|
Finally, here's some code that uses the variable. It assigns it to point to each of the three functions and calls each.
|
|
func = AddressOf A
Debug.WriteLine("A: " & func(10))
func = AddressOf B
Debug.WriteLine("B: " & func(10))
func = AddressOf C
Debug.WriteLine("C: " & func(10))
|
|
And here are the results:
|
|
A: 11
B: 20
C: 100
|
|
|
|