typestar

Events in Visual Basic

Event, RaiseEvent and the AddHandler wiring in one kettle.

Dim pot As New Kettle()
Dim onBoil = Sub(d As Integer) Console.WriteLine($"whistling at {d}C")

AddHandler pot.Boiled, onBoil
pot.Heat()
RemoveHandler pot.Boiled, onBoil
pot.Heat()
Console.WriteLine("silent this time")

Class Kettle
    Public Event Boiled(degrees As Integer)

    Public Sub Heat()
        For temp = 60 To 100 Step 20
            If temp = 100 Then RaiseEvent Boiled(temp)
        Next
    End Sub
End Class

How it works

  1. Public Event Boiled(...) declares the signal and its signature.
  2. RaiseEvent fires every handler currently attached.
  3. AddHandler wires a lambda in; RemoveHandler takes the same one out.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
386
Tokens
94
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 70 seconds.

Type this snippet

Step 3 of 3 in VB idioms, step 24 of 29 in Language basics.

← Previous Next →

Events in other languages