Syntax [accessModifier] [Shadows] Delegate { Sub | Function } name _ [(Of typeParamList)] [([argList])] [As type]
accessModifier (optional) Specifies the scope and accessibility of the delegate. One of the following access levels: Access level | Description |
---|
Public | The delegate is publicly accessible anywhere, both inside and outside of the project. | Private | The delegate is accessible only within the defining type. | Protected | The delegate is accessible only to the code in the defining type or to one of its derived types. | Friend | The delegate is accessible only within the project that contains the delegate definition. | Protected Friend | Combines the access features of Protected and Friend. |
If omitted, the Public access level is used.
Shadows (optional) Indicates that the delegate shadows an identically named element in a base class.
name (required) The name of the delegate. It need not match the target procedure or function name.
typeParamList (optional) Adds type parameter placeholders that will later enforce strong typing when the delegate is used. The Of clause implements generics, which are fully described in Chapter 10. If generics will not be used, this clause can be excluded.
argList (optional; any) The argument list specific to this delegate. It must have the same signature as the target procedure or function, although the names of each argument need not match.
type (optional; any) The return type of the function-associated delegate. The As clause is only used for function parameters; it is excluded when defining a procedure delegate. Description The Delegate statement declares the parameters and return type of a delegate. The syntax is similar to that used to declare subroutines and functions. Usage at a Glance Any procedure with an argument list and return type that match that of a declared delegate class can be used to create an instance of this delegate class. For more information on delegates, see Chapter 8. Example Consider the following class definition: Public Class SimpleClass Public Sub SimpleMethod(ByVal onlyArg As String) MsgBox(onlyArg) End Sub End Class A delegate can be defined that carries the same signature as the SimpleMethod procedure. Delegate Sub MatchingDelegate(ByVal anyArg As String) The following code uses the delegate to call the SimpleClass.SimpleMethod member: Private Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button1.Click ' ----- Call a method through a delegate. Dim classInstance As New SimpleClass Dim theDelegate As MatchingDelegate ' ----- Define the delegate, passing the address of the ' object's method, which has a matching signature. theDelegate = New MatchingDelegate(AddressOf _ classInstance.SimpleMethod) ' ----- Use Invoke to call the method. theDelegate.Invoke("test") End Sub Version Differences See Also Function Statement, Sub Statement |