What are the differences, side effects, and/or preferences of these 2 different ways of adding an event handler for the SQLConnection.StateChange event? Since AddressOf creates a delegate (http://msdn.microsoft.com/en-us/library/y72ewk2b.aspx), and StateChangeEventHandler is a delegate as well, example 2 seems to just be creating nested delegates, but I'm guessing that there is some nuance that I'm missing.
From my testing they appear to work the same using either example 1 or 2. Neither throw an exception when attempting to call AddHandler more than once (my first assumption was that calling example #1 would throw an error if attempting to call AddHandler a second time since it would be adding the same reference, as where example 2 would not since it would be a new delegate instance; however, they both succeed without an exception).
Example 1: Using only AddressOf: http://msdn.microsoft.com/en-us/library/7taxzxka.aspx
AddHandler conn.StateChange, AddressOf OnConnectionStateChange
Example 2: Using an instance of the StateChangeEventHandler delegate as listed here: http://msdn.microsoft.com/en-us/library/a0hee08w(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
AddHandler conn.StateChange, New StateChangeEventHandler(AddressOf OnConnectionStateChange)
Also, is there a need to remove this handler prior to dispose/end of the using block via RemoveHandler, or will SQLConnection.Dispose take care of that for you? I'm not sure how you would remove the event handler if using the StateChangeEventHandler in example #2 below from the MSDN site, since the instance of StateChangeEventHandler delegate is not stored in a local variable, so you have no reference of the handler to remove (you would have to do something similar to Example #4).
Example #3: RemoveHandler using just AddressOf
Using conn As SqlConnection = New SqlConnection("...")
AddHandler conn.StateChange, AddressOf OnConnectionStateChange
conn.Open()
'...do work here...
conn.Close()
'Then do i need this?
RemoveHandler conn.StateChange, AddressOf OnConnectionStateChange
End Using
Example #4: RemoveHandler using the StateChangeEventHandler
Using conn As SqlConnection = New SqlConnection("...")
Dim myHandler As StateChangeEventHandler = New StateChangeEventHandler(AddressOf OnConnectionStateChange)
AddHandler conn.StateChange, myHandler
conn.Open()
'...do work here...
conn.Close()
'Then do i need this?
RemoveHandler conn.StateChange, myHandler
End Using
NOTE: I tagged as C# as well since the MSDN documentation also lists the same scenario for the C# example:
connection.StateChange += new StateChangeEventHandler(OnStateChange);
vs.
connection.StateChange += OnStateChange;