Calling a function from a variable (using delegates)
I wanted to share this code with my readers. I recently answered a post on vbcity.net where Cindi asked:
I have a class called HardDate that will include 70 different functions.
Each function is a symbol that will match the data that I will be iterating through..
For example.. SP, HO & HU are the symbols.
So I will be able to call the following 3 functions
Code:
Dim Value1, Value2, Value3 as int16
Dim HD as HardDate
Value1=HD.SP
Value2=HD.HO
Value3=HD.HU
Is there a way for me to pass a variable as the function name?
Code:
Dim Value1 as int16
Dim HD as HardDate
Dim iSym as string = “SP”
Value1=HD.iSym 'which will simply call HD.SP
Or am I going to have to find another way around this that will need to list out all 70 functions as in a "Select Case" or "ElseIF"?
Can I create an object array that holds all 70 functions can call it by its index number??
I don't know what my options are.. but there must be a better way of doing it then listing out all 70 functions..
My Response:
You need a delegate. Think of a Delegate as an object that represents a method call and can be passed around like any other variable.
Create a form and put two buttons on it. Here is some sample code:
Public Class Form1
Inherits System.Windows.Forms.Form
'#Region " Windows Form Designer generated code " REMOVED
'-- This is really a data type that represents a function call having a single string argument.
' Create others for subs that have different argument lists (or signatures)
Private Delegate Sub dlgSingleString(ByVal Arg As String)
'-- Create a new object that has the methods you want to call
Dim tc As New TestClass
'-- These variables represent the function calls
Dim dlg1 As dlgSingleString
Dim dlg2 As dlgSingleString
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'-- The dlgSingleString objects are created with the address of a method (could be local, global, or in any object)
dlg1 = New dlgSingleString(AddressOf tc.Sub1)
dlg2 = New dlgSingleString(AddressOf tc.Sub2)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'-- Call the first sub
dlg1.Invoke("Hello Sub 1")
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'-- Call the second sub
dlg2.Invoke("Hello Sub 2")
End Sub
End Class
Public Class TestClass
'-- Simple class with two subs
Public Sub Sub1(ByVal Arg As String)
MsgBox("Sub1: " & Arg)
End Sub
Public Sub Sub2(ByVal Arg As String)
MsgBox("Sub2: " & Arg)
End Sub
End Class