Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This example shows how to use delegates to pass a procedure to another procedure.
A delegate is a type that you can use like any other type in Visual Basic. The AddressOf operator returns a delegate object when applied to a procedure name.
This example has a procedure with a delegate parameter that can take a reference to another procedure, obtained with the AddressOf operator.
Create the delegate and matching procedures
Create a delegate named
MathOperator.Delegate Function MathOperator( ByVal x As Double, ByVal y As Double ) As DoubleCreate a procedure named
AddNumberswith parameters and return value that match those ofMathOperator, so that the signatures match.Function AddNumbers( ByVal x As Double, ByVal y As Double ) As Double Return x + y End FunctionCreate a procedure named
SubtractNumberswith a signature that matchesMathOperator.Function SubtractNumbers( ByVal x As Double, ByVal y As Double ) As Double Return x - y End FunctionCreate a procedure named
DelegateTestthat takes a delegate as a parameter.This procedure can accept a reference to
AddNumbersorSubtractNumbers, because their signatures match theMathOperatorsignature.Sub DelegateTest( ByVal x As Double, ByVal op As MathOperator, ByVal y As Double ) Dim ret As Double ret = op.Invoke(x, y) ' Call the method. MsgBox(ret) End SubCreate a procedure named
Testthat callsDelegateTestonce with the delegate forAddNumbersas a parameter, and again with the delegate forSubtractNumbersas a parameter.Protected Sub Test() DelegateTest(5, AddressOf AddNumbers, 3) DelegateTest(9, AddressOf SubtractNumbers, 3) End SubWhen
Testis called, it first displays the result ofAddNumbersacting on5and3, which is 8. Then the result ofSubtractNumbersacting on9and3is displayed, which is 6.