Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleUse a variable to hold delegates (function pointers) in Visual Basic 2005
DescriptionThis example shows how to use a variable to hold delegates (function pointers) in Visual Basic 2005.
Keywordsdelegate, function pointer, function reference, method pointer, methd reference, Visual Basic 2005
CategoriesSoftware 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
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated