Search code examples
.netvb.neteventsevent-handlinghandles

Does WithEvents in Visual Basic keep its EventHandlers when changing the reference to the object?


Does WithEvents in Visual Basic keep its EventHandlers when changing the reference to the object?

Say I have declared a button, firing events:

Private WithEvents _MyButton

Now I am subscribing to an event handler:

Private Sub _MyButton_Click() Handles _MyButton.Click 
  ' Here I DoClick()
End Sub

Will the DoClick() function be still called when I change the instance of the button object like shown below?

_MyButton = New Button()

Solution

  • This got me curious so I wrote a small console application to visualize what happens if you do this experiment using a timer:

    Private WithEvents _t As New Timers.Timer With {.Enabled = True}
    Private Sub _t_Elapsed(sender As Object, e As Timers.ElapsedEventArgs) Handles _t.Elapsed
        Console.WriteLine("tick")
    End Sub
    
    Sub Main()
        ' let it tick for 5 seconds
        Task.Delay(5000).Wait()
    
        ' destroy the current timer
        Console.WriteLine("destroying this timer")
        _t.Dispose()
        _t = Nothing
    
        ' add a little pause
        Task.Delay(1000).Wait()
    
        ' create a new timer
        Console.WriteLine("creating a new timer")
        _t = New Timers.Timer With {.Enabled = True}
    
        ' let it tick for 5 seconds
        Task.Delay(5000).Wait()
    
    End Sub
    

    If you run this code, you will find that it does indeed attach the event handler when the instance of _t is replaced. I don't know how it does that, but the magic probably lies in the Handles keyword. Anyhow, the answer is yes.