How to: Pass Procedures to Another Procedure in Visual Basic
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.
Create a procedure named AddNumbers with parameters and return value that match those of MathOperator, so that the signatures match.
Create a procedure named SubtractNumbers with a signature that matches MathOperator.
Create a procedure named DelegateTest that takes a delegate as a parameter.
This procedure can accept a reference to AddNumbers or SubtractNumbers, because their signatures match the MathOperator signature.
Create a procedure named Test that calls DelegateTest once with the delegate for AddNumbers as a parameter, and again with the delegate for SubtractNumbers as a parameter.
When Test is called, it first displays the result of AddNumbers acting on 5 and 3, which is 8. Then the result of SubtractNumbers acting on 9 and 3 is displayed, which is 6.