description | title | ms.date | helpviewer_keywords | ms.assetid | ||
---|---|---|---|---|---|---|
Learn more about: How to: Pass Procedures to Another Procedure in Visual Basic |
How to: Pass Procedures to Another Procedure |
07/20/2015 |
|
5adbba15-5a1d-413f-ab3e-3ff6cc0a4669 |
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 a delegate named
MathOperator
.[!code-vbVbVbalrDelegates#1]
-
Create a procedure named
AddNumbers
with parameters and return value that match those ofMathOperator
, so that the signatures match.[!code-vbVbVbalrDelegates#2]
-
Create a procedure named
SubtractNumbers
with a signature that matchesMathOperator
.[!code-vbVbVbalrDelegates#3]
-
Create a procedure named
DelegateTest
that takes a delegate as a parameter.This procedure can accept a reference to
AddNumbers
orSubtractNumbers
, because their signatures match theMathOperator
signature.[!code-vbVbVbalrDelegates#4]
-
Create a procedure named
Test
that callsDelegateTest
once with the delegate forAddNumbers
as a parameter, and again with the delegate forSubtractNumbers
as a parameter.[!code-vbVbVbalrDelegates#5]
When
Test
is called, it first displays the result ofAddNumbers
acting on5
and3
, which is 8. Then the result ofSubtractNumbers
acting on9
and3
is displayed, which is 6.