Lessons in this course (12)

8. Events and delegates — WithEvents, Handles, AddHandler, RaiseEvent

Intermediate★ Must knowLesson 8 of 12
vb
Public Class Thermostat
    Public Event TooHot As EventHandler(Of Double)          ' declare an event
    Public Sub Read(temp As Double)
        If temp > 40 Then RaiseEvent TooHot(Me, temp)        ' raise it (no null check needed)
    End Sub
End Class

' Style 1: WithEvents + Handles (static wiring — typical in WinForms/Web Forms code-behind)
Public Class Monitor
    Private WithEvents _sensor As New Thermostat()
    Private Sub OnTooHot(sender As Object, t As Double) Handles _sensor.TooHot
        Console.WriteLine($"Alert {t}")
    End Sub
End Class

' Style 2: AddHandler / RemoveHandler (dynamic wiring = C# += / -=)
Dim th As New Thermostat()
AddHandler th.TooHot, AddressOf OnTooHot                     ' AddressOf = method group
AddHandler th.TooHot, Sub(s, t) Console.WriteLine($"Lambda {t}")
RemoveHandler th.TooHot, AddressOf OnTooHot

' Custom delegate type
Public Delegate Function Calc(a As Integer, b As Integer) As Integer
Dim add As Calc = Function(a, b) a + b

In Web Forms VB code-behind you'll see Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click — the Handles clause connects the button's server event.