Used to declare a delegate. A delegate is a reference type that refers to a Shared method of a type or to an instance method of an object. Any procedure with matching parameter and return types can be used to create an instance of this delegate class. The procedure can then later be invoked by means of the delegate instance.
[ <attrlist> ] [ accessmodifier ] _ [ Shadows ] Delegate [ Sub | Function ] name [( Of typeparamlist )] [([ parameterlist ])] [ As type ]
The Delegate statement defines the parameter and return types of a delegate class. Any procedure with matching parameters and return types can be used to create an instance of this delegate class. The procedure can then later be invoked by means of the delegate instance, by calling the delegate's Invoke method.
Delegates can be declared at the namespace, module, class, or structure level, but not within a procedure.
Each delegate class defines a constructor that is passed the specification of an object method. An argument to a delegate constructor must be a reference to a method, or a lambda expression.
To specify a reference to a method, use the following syntax:
The compile-time type of the expression must be the name of a class or an interface that contains a method of the specified name whose signature matches the signature of the delegate class. The methodname can be either a shared method or an instance method. The methodname is not optional, even if you create a delegate for the default method of the class.
To specify a lambda expression, use the following syntax:
Function ([parm As type, parm2 As type2, ...]) expression
The signature of the function must match that of the delegate type. For more information about lambda expressions, see Lambda Expressions.
The following example uses the Delegate statement to declare a delegate for operating on two numbers and returning a number. The DelegateTest method takes an instance of a delegate of this type and uses it to operate on pairs of numbers.
Delegate Function MathOperator( _ ByVal x As Double, _ ByVal y As Double _ ) As Double Function AddNumbers( _ ByVal x As Double, _ ByVal y As Double _ ) As Double Return x + y End Function Function SubtractNumbers( _ ByVal x As Double, _ ByVal y As Double _ ) As Double Return x - y End Function 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 Sub Protected Sub Test() DelegateTest(5, AddressOf AddNumbers, 3) DelegateTest(9, AddressOf SubtractNumbers, 3) End Sub