I stumbled upon this article (http://msdn.microsoft.com/en-us/library/74wy9422(v=vs.90).aspx) which mentions that AddressOf is simply short-hand for New EventHandler(AddressOf fn).
AddHandler Button1.Click, New EventHandler(AddressOf Button1_Click)
' The following line of code is shorthand for the previous line.
AddHandler Button1.Click, AddressOf Me.Button1_Click
and it also states:
You can use the shorthand way of creating delegates anywhere the compiler can determine the delegate's type by the context
So in most cases, using New SomeEventHandlerType(AddessOf x)
or just AddressOf x
accomplishes the same thing. In the case of SQLConnection.StateChange
, the event is Declared as Public Event StateChange As StateChangeEventHandler
, so the compiler knows the correct delegate type to use, and AddressOf
is smart enough to use the correct delegate type automatically for you. There is no need to use New StateChangeEventHandler(AddressOf OnConnectionStateChange)
, but it can be used for code clarity to show that this is not the generic EventHandler delegate type, and that it uses a custom EventArgs type.
As far as unsubscribing, to be absolutely certain to avoid resource leaks, you should remove event handler references before disposing of the subscriber object. See http://msdn.microsoft.com/en-us/library/ms366768(v=vs.120).aspx which states:
In order to prevent resource leaks, you should unsubscribe from events before you dispose of a subscriber object. Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, garbage collection will not delete your subscriber object.
In actual practice, I've seen very few examples that do this (even in the MSDN "How to: Publish Events that Conform to .NET Framework Guidelines" http://msdn.microsoft.com/en-us/library/w369ty8x.aspx). GC will take care of removing event references on the publisher when it is finalized. However, if you have scenarios where the publisher can live much longer than the subscriber, you will need to make sure the remove the event references manually. In the SQLConnection example, the connection object (i.e. the publisher of the StateChange event) has a short lifetime, so the RemoveHandler
is arguably not needed. See this post for more details: .NET object events and dispose / GC