MSDN Documentation

Delegates and Events in Visual Basic .NET

Delegates are type-safe function pointers that enable methods to be passed as parameters, stored in variables, and invoked dynamically. Events build on delegates to provide a publish/subscribe pattern for communication between objects.

Defining a Delegate

Public Delegate Sub SimpleDelegate(ByVal sender As Object, ByVal e As EventArgs)

Using a Delegate

Public Class Calculator
    Private _calcHandler As SimpleDelegate

    Public Sub RegisterHandler(handler As SimpleDelegate)
        _calcHandler = handler
    End Sub

    Public Sub Add(a As Integer, b As Integer)
        Dim result = a + b
        _calcHandler?.Invoke(Me, New EventArgs())
        Console.WriteLine($"Result: {result}")
    End Sub
End Class

Defining an Event

Public Class Publisher
    ' Declare the event using the built‑in EventHandler delegate
    Public Event DataProcessed As EventHandler

    Public Sub Process()
        ' Simulate work
        Threading.Thread.Sleep(500)
        ' Raise the event
        RaiseEvent DataProcessed(Me, EventArgs.Empty)
    End Sub
End Class

Subscribing to an Event

Public Class Subscriber
    Public Sub New(p As Publisher)
        AddHandler p.DataProcessed, AddressOf OnDataProcessed
    End Sub

    Private Sub OnDataProcessed(sender As Object, e As EventArgs)
        Console.WriteLine("Data processed event received.")
    End Sub
End Class

Full Example

Module Module1
    Sub Main()
        Dim pub As New Publisher()
        Dim sub As New Subscriber(pub)

        Console.WriteLine("Starting process...")
        pub.Process()
        Console.WriteLine("Process finished.")

        ' Demo delegate usage
        Dim calc As New Calculator()
        calc.RegisterHandler(AddressOf OnCalcCompleted)
        calc.Add(5, 7)

        Console.ReadLine()
    End Sub

    Private Sub OnCalcCompleted(sender As Object, e As EventArgs)
        Console.WriteLine("Calculation completed.")
    End Sub
End Module

Run the code above to see how delegates and events work together to decouple components.

Key Points