Delegates
Delegates are type-safe function pointers. They allow you to pass methods as parameters to other methods, store methods in variables, and create callback methods. Delegates are fundamental to event handling and the implementation of many .NET Framework features.
What is a Delegate?
A delegate is a reference type that specifies a signature (return type and parameter types) and is used to declare methods that match that signature. Once a delegate type is declared, you can create instances of that delegate type. These instances can refer to any method that has the same parameter list and return type as the delegate.
Declaring a Delegate
You declare a delegate using the Delegate
keyword:
Public Delegate Sub MyDelegate(ByVal message As String)
In this example, MyDelegate
is a delegate type that can refer to any Sub
procedure that takes a single String
argument.
Instantiating a Delegate
You create an instance of a delegate by associating it with a method that matches its signature:
' Assuming you have a Sub named PrintMessage that matches the delegate's signature
Dim handler As MyDelegate = AddressOf PrintMessage
The AddressOf
operator returns a delegate object that refers to the specified method.
Invoking a Delegate
You invoke a delegate just as you would call a method:
handler("Hello, Delegates!")
This will execute the PrintMessage
procedure.
Multicast Delegates
Delegates can be chained together to form a multicast delegate. A multicast delegate holds references to multiple methods. When a multicast delegate is invoked, all methods referenced by it are invoked.
You can add methods to a multicast delegate using the addition assignment operator (+=
):
' Assuming you have another Sub named PrintMessageUpper
handler += AddressOf PrintMessageUpper
When handler
is invoked now, both PrintMessage
and PrintMessageUpper
will be called.
You can remove methods from a multicast delegate using the subtraction assignment operator (-=
):
handler -= AddressOf PrintMessageUpper
Common Use Cases
- Event Handling: Delegates are the backbone of the event model in .NET. When an event occurs, the delegate associated with that event is invoked, triggering the event handler methods.
- Callbacks: You can pass a delegate to a method to specify a callback function that the method can invoke later, for example, to report progress or completion.
- Asynchronous Operations: Delegates are used with asynchronous programming patterns to handle the results of operations that run on separate threads.
Example: Event Handling with Delegates
Consider a button control that raises a click event. The button class would likely have a delegate type defined for its click event, and when the button is clicked, it invokes this delegate, passing itself as the sender and event arguments.
' Example Delegate Declaration
Public Delegate Sub ButtonClickHandler(sender As Object, e As EventArgs)
' Example Class using the Delegate for an Event
Public Class Button
Public Event Click As ButtonClickHandler
Public Sub SimulateClick()
' When the button is clicked, raise the event
' The 'RaiseEvent' keyword invokes the delegate
RaiseEvent Click(Me, EventArgs.Empty)
End Sub
End Class
' Example Usage
Module Module1
Sub Main()
Dim myButton As New Button()
AddHandler myButton.Click, AddressOf OnButtonClick
myButton.SimulateClick()
End Sub
Sub OnButtonClick(sender As Object, e As EventArgs)
Console.WriteLine("Button was clicked!")
End Sub
End Module
This example demonstrates how a delegate (ButtonClickHandler
) is used to define the signature for an event (Click
), allowing other parts of the application to subscribe to and handle the button's click event.