Events in Visual Basic

Events are a fundamental part of building responsive applications in Visual Basic. They allow objects to notify other objects or the user interface when something significant happens. This is crucial for creating interactive experiences.

What are Events?

An event is a notification sent by an object to signal that a particular occurrence has happened. For example, a button click, a mouse movement, or a timer tick can all be represented as events. The object that raises an event is called the publisher, and the object that responds to the event is called the subscriber.

Declaring Events

You declare an event in a class using the Event keyword. You can also define the signature of the event using a delegate.

Using the EventHandler Delegate

The System.EventHandler delegate is commonly used for events that don't require custom data. It has a signature that accepts an Object (the sender) and an EventArgs object.

VB.NET

Public Class Publisher
    ' Declare an event using the EventHandler delegate
    Public Event MySimpleEvent As EventHandler

    Public Sub TriggerSimpleEvent()
        ' Raise the event
        RaiseEvent MySimpleEvent(Me, EventArgs.Empty)
    End Sub
End Class
            

Custom Event Arguments

For events that need to pass specific data, you can create a custom class that inherits from EventArgs.

VB.NET

' Define custom EventArgs
Public Class MyCustomEventArgs
    Inherits EventArgs

    Public ReadOnly Property Message As String
    Public ReadOnly Property Value As Integer

    Public Sub New(message As String, value As Integer)
        Me.Message = message
        Me.Value = value
    End Sub
End Class

' Declare an event using a custom delegate
Public Delegate Sub MyCustomEventHandler(sender As Object, e As MyCustomEventArgs)

Public Class PublisherWithData
    ' Declare an event using the custom delegate
    Public Event MyDataEvent As MyCustomEventHandler

    Public Sub TriggerDataEvent(message As String, value As Integer)
        ' Create an instance of custom EventArgs
        Dim eventArgs As New MyCustomEventArgs(message, value)
        ' Raise the event
        RaiseEvent MyDataEvent(Me, eventArgs)
    End Sub
End Class
            

Handling Events

To respond to an event, you subscribe to it using the AddHandler statement. The event handler must match the signature of the delegate used to declare the event.

VB.NET

Public Class Subscriber
    Public Sub SubscribeToEvents()
        Dim publisherSimple As New Publisher()
        Dim publisherData As New PublisherWithData()

        ' Subscribe to the simple event
        AddHandler publisherSimple.MySimpleEvent, AddressOf HandleSimpleEvent

        ' Subscribe to the custom data event
        AddHandler publisherData.MyDataEvent, AddressOf HandleDataEvent

        ' Trigger the events
        publisherSimple.TriggerSimpleEvent()
        publisherData.TriggerDataEvent("Important Update", 42)
    End Sub

    ' Event handler for the simple event
    Private Sub HandleSimpleEvent(sender As Object, e As EventArgs)
        Console.WriteLine("Simple event received!")
        ' You can inspect the sender if needed
        ' Dim pub As Publisher = CType(sender, Publisher)
    End Sub

    ' Event handler for the custom data event
    Private Sub HandleDataEvent(sender As Object, e As MyCustomEventArgs)
        Console.WriteLine($"Data event received: {e.Message}, Value: {e.Value}")
    End Sub
End Class
            

Unsubscribing from Events

It's good practice to unsubscribe from events when they are no longer needed to prevent memory leaks. Use the RemoveHandler statement.

VB.NET

' Assuming 'publisherSimple' is an instance of the Publisher class
' and 'HandleSimpleEvent' is a valid handler
RemoveHandler publisherSimple.MySimpleEvent, AddressOf HandleSimpleEvent
            

Common Scenarios and Best Practices

Important: Always ensure that the sender object passed to the event handler is correctly cast to its actual type if you need to access its members.
Tip: For more complex scenarios, consider using the Async Await pattern in conjunction with events to handle asynchronous operations smoothly.

Summary

Events provide a powerful mechanism for communication between objects in Visual Basic. By understanding how to declare, raise, and handle events, you can build dynamic and responsive applications.

Further Reading