Monday, May 15, 2023

Pop quiz on Event Handlers

Just for fun, I wrote this console app in Visual Basic that adds two identical event handlers and declares a method as Handles. Then I kept raising the event while calling RemoveHandler. See if you can guess what the output will be.

Imports System
 
Module Program
    Dim WithEvents c As New DemoClass()
    Sub Main(args As String())
        Console.WriteLine("-------------------------------")
        Console.WriteLine("Add Handlers")
        AddHandler c.SaySomething, AddressOf SaySomething
        AddHandler c.SaySomething, AddressOf SaySomething
        c.TalkToMe("Two handlers")
        Console.WriteLine("Remove Handler")
        RemoveHandler c.SaySomething, AddressOf SaySomething
        c.TalkToMe("One handler")
        Console.WriteLine("Remove Handler")
        RemoveHandler c.SaySomething, AddressOf SaySomething
        c.TalkToMe("No handlers")
        Console.WriteLine("Remove Handles")
        RemoveHandler c.SaySomething, AddressOf SaySomethingElse
        c.TalkToMe("Not even Handles")
        Console.WriteLine("Press Enter to exit")
        Console.ReadLine()
    End Sub
 
    Private Sub SaySomething(Something As String)
        Console.WriteLine($"Say {Something}")
    End Sub
 
    Private Sub SaySomethingElse(Something As String) Handles c.SaySomething
        Console.WriteLine($"Also Say {Something}")
    End Sub
 
    Public Class DemoClass
        Public Event SaySomething(Something As String)
        Public Sub TalkToMe(Something As String)
            RaiseEvent SaySomething(Something)
        End Sub
    End Class
End Module

The result is that RemoveHandler only removes one of a duplicate pair of handlers. I don't know which one and I don't think it matters. Note the handler declared with Handles is raised before the ones declared with AddHandler, which makes sense. Even more interestingly RemoveHandler will also remove the handler that was declared with Handles. I did not know that. Did you?






No comments:

Post a Comment