Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Classes and Objects

Events and Delegates

Learn events in Visual Basic .NET: delegates, Event and RaiseEvent, WithEvents with Handles, AddHandler and RemoveHandler, EventArgs, and Action/Func delegates, including the observer pattern and common pitfalls.

An event lets an object tell the outside world that something happened, without knowing who is listening. A button raises Click, a download raises Progress, a timer raises Tick. Windows Forms and WPF programs are built on events, which is why this is essential before the GUI chapter. Events are built on delegates, which are type-safe references to methods. Listings are VB.NET (read-only); runnable C# stand-ins use the same delegate and event machinery.

Delegates: a variable that holds a method

A delegate type describes a method signature. A delegate variable can point at any method (or several) with that signature, and calling the variable calls the method.

VB
Delegate Function Operation(a As Integer, b As Integer) As Integer

Function Add(a As Integer, b As Integer) As Integer
    Return a + b
End Function

Function Multiply(a As Integer, b As Integer) As Integer
    Return a * b
End Function

Sub Main()
    Dim op As Operation = AddressOf Add      ' AddressOf makes a delegate to a method
    Console.WriteLine(op(3, 4))              ' 7
    op = AddressOf Multiply
    Console.WriteLine(op.Invoke(3, 4))       ' 12
End Sub

In practice you rarely declare delegate types yourself. The framework provides generic ones: Action(Of ...) for methods that return nothing and Func(Of ..., TResult) for methods that return a value. Lambdas create them inline:

VB
Dim add As Func(Of Integer, Integer, Integer) = Function(a, b) a + b
Dim log As Action(Of String) = Sub(msg) Console.WriteLine("LOG: " & msg)

A delegate can hold several methods at once (a multicast delegate). Calling it runs them in order.

C# Stand-in (C#): delegates, Func and multicast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Declaring and raising events

An event is a delegate with restricted access: outside code can only subscribe and unsubscribe, not invoke the event or wipe the subscriber list. The declaring class raises it with RaiseEvent.

VB
Public Class Thermostat
    Public Event TemperatureChanged(oldValue As Double, newValue As Double)

    Private _current As Double = 20

    Public Property Current As Double
        Get
            Return _current
        End Get
        Set(value As Double)
            If value <> _current Then
                Dim old = _current
                _current = value
                RaiseEvent TemperatureChanged(old, value)
            End If
        End Set
    End Property
End Class

Event Name(parameters) declares the event and its signature in one line; VB creates the hidden delegate type for you. RaiseEvent does nothing when nobody is subscribed, so no null check is needed.

The standard pattern with EventArgs

.NET convention uses (sender As Object, e As EventArgs) signatures so handlers look alike everywhere. Put your data in a class that inherits EventArgs:

VB
Public Class PriceChangedEventArgs
    Inherits EventArgs
    Public ReadOnly Property OldPrice As Decimal
    Public ReadOnly Property NewPrice As Decimal
    Public Sub New(oldPrice As Decimal, newPrice As Decimal)
        Me.OldPrice = oldPrice
        Me.NewPrice = newPrice
    End Sub
End Class

Public Class Stock
    Public Event PriceChanged As EventHandler(Of PriceChangedEventArgs)
    ' ... RaiseEvent PriceChanged(Me, New PriceChangedEventArgs(oldP, newP))
End Class

Handling events: WithEvents and AddHandler

VB offers two ways to subscribe.

1. WithEvents and Handles (static wiring). Declare a field WithEvents, then mark a handler with Handles. The subscription is automatic for the field's whole lifetime. Windows Forms designers generate this style:

VB
Public Class Monitor
    Private WithEvents _thermostat As New Thermostat()

    Private Sub OnChanged(oldValue As Double, newValue As Double) Handles _thermostat.TemperatureChanged
        Console.WriteLine($"Temperature {oldValue} -> {newValue}")
    End Sub

    Public Sub Run()
        _thermostat.Current = 23
    End Sub
End Class

2. AddHandler and RemoveHandler (dynamic wiring). Subscribe at run time, to any object, and unsubscribe later:

VB
Dim t As New Thermostat()
Dim handler As Thermostat.TemperatureChangedEventHandler =
    Sub(o, n) Console.WriteLine($"Now {n}")

AddHandler t.TemperatureChanged, handler
t.Current = 25                          ' prints "Now 25"
RemoveHandler t.TemperatureChanged, handler
t.Current = 26                          ' nobody listening

AddHandler t.TemperatureChanged, AddressOf OnChanged also works with a named method. Several handlers may subscribe to one event; they run in the order they were added.

C# Stand-in (C#): an event with subscribe and unsubscribe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The observer pattern

Events implement the observer pattern: a subject keeps no knowledge of its observers except that they subscribed. The subject stays simple and testable, and you can add observers (a logger, an alarm, a UI label) without touching it.

flowchart LR
    S["Thermostat<br/>(raises event)"] -- TemperatureChanged --> A["Logger"]
    S -- TemperatureChanged --> B["Alarm"]
    S -- TemperatureChanged --> C["Display label"]

Figure: one event, many independent subscribers.

Pitfalls

  • Memory leaks. A subscriber is kept alive by the publisher's event list. If a short-lived object subscribes to a long-lived one, call RemoveHandler (or dispose the subscriber), or the garbage collector cannot free it.
  • Exceptions in handlers stop later handlers from running, and propagate to the code that raised the event.
  • Slow handlers block the raiser: events run synchronously on the raising thread.
  • Threads: a handler runs on the thread that raised the event. In Windows Forms you must switch to the UI thread before touching controls (see the Windows Forms chapter).
  • Order of handlers is the order of subscription but should not be relied upon.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a delegate?

    A delegate variable can hold and call one or more methods that match its signature.
  2. 2. Which statement raises a VB event named Finished?

    VB events are raised with RaiseEvent, which does nothing when there are no subscribers.
  3. 3. How do you subscribe to an event at run time?

    AddHandler subscribes dynamically; RemoveHandler undoes it. Handles needs a WithEvents field.
  4. 4. What problem can a forgotten subscription cause?

    The publisher's event list holds references to subscribers, so they cannot be collected.
  5. 5. In what order do multiple handlers of one event run?

    Multicast delegates invoke subscribers in subscription order, on the raising thread.

Summary

  • Delegates reference methods; Action and Func cover most needs; lambdas create them inline.
  • Declare events with Event, raise them with RaiseEvent, and use EventArgs subclasses for data.
  • Subscribe statically with WithEvents and Handles, or dynamically with AddHandler and RemoveHandler.
  • Events implement the observer pattern; unsubscribe long-lived publishers to avoid leaks and remember handlers run synchronously.

Next: Structures, Enums and Generics