VB.NET Event Handlers

I was just listening to Bill McCarthy chatting with Ron Jacobs on Arcast about the rich feature set of VB 2005.  One of the points of interest was around the declarative approach to event handlers that VB.NET uses.  For example say I have the following class with an event declaration:

Public Class ClassWithAnEvent

Public Event TestEvent As EventHandler

End Class

Now in VB.NET to wire up an object of this class so that I can receive notification on the TestEvent I can do it declaratively as follow:

Public Class ClassThatConsumesAnEvent

Private WithEvents x As ClassWithAnEvent

Private Sub TestEventHandler(ByVal sender As Object, ByVal e As EventArgs) Handles x.TestEvent

End Sub

End Class

The question is what does this do under the hood.  Well the easiest way to explain this is using our good friend, Reflector, to regenerate the code:

Public Class ClassThatConsumesAnEvent

<AccessedThroughProperty(“x”)> _
Private _x As ClassWithAnEvent

Private Overridable Property x As ClassWithAnEvent

Get

    Return Me._x

End Get

Set(ByVal WithEventsValue As ClassWithAnEvent)

    If (Not Me._x Is Nothing) Then

    RemoveHandler Me._x.TestEvent, New EventHandler(AddressOf Me.TestEventHandler)

    End If

    Me._x = WithEventsValue

    If (Not Me._x Is Nothing) Then

    AddHandler Me._x.TestEvent, New EventHandler(AddressOf Me.TestEventHandler)

    End If

End Set

End Property

End Class

As we can see from this code, VB.NET is doing a lot of the heavy lifting around adding and removing eventhandlers.  This means that we can easily reassign an object to variable x without having to worry about adding and removing eventhandlers.  This also clears up, for those that were wondering, where eventhandlers are added/removed in VB.NET.

Leave a comment