views:

160

answers:

2

Understood that Handles is only a way to add in constructor the AddHandler, but in general these two are equivalent.

True?

+1  A: 

There is some difference in exactly when the event handler is attached, and what is going on around it. For instance, when using WithEvents and Handles, the compiler will emit code that wraps access to the variable holding the instance that exposes the event in a property, and inside the property setter it will detach the event handler from the previous instance (if any), and then attach the event handler to the new instance (if any).

This means that if you take the following code samples, the access to mm will behave differently:

' WithEvents approach '
Dim WithEvents mm As SomeClass
Sub Main()
    mm = New SomeClass()
    Dim nn As SomeClass = mm
End Sub

' Other approach '
Dim mm As SomeClass
Sub Main()
    mm = New SomeClass()
    Dim nn As SomeClass = mm
End Sub

In the WithEvents case, mm = New SomeClass() will in fact call a property setter, and Dim nn As SomeClass = mm will fetch the value from a property getter, while in the second case, there will be no property created for the value, but the code will access the field directly.

Fredrik Mörk
in other words, using **AddHanlder** is optimal for the, let's say, *resources* and speed, and **WithEvents** for the code *readability*?..
serhio
And what about detaching the event handler when the object has no more references to it?
serhio
@serhio: I think that the increased readability of using `WithEvents` may be debated, but in general I think you are right. `WithEvents` also has the mechanism of detaching event handlers when you set the field to `Nothing`, which is nice (if you fail to detach event handlers, they will prevent the object from being garbage collected).
Fredrik Mörk
one little precision: If I replace somewhere `mm = otherInstanceOfSomeClass`, will always the new mm follow the events?
serhio
@serhio: yes, that is correct.
Fredrik Mörk
A: 
Private Sub Button1_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) Handles Button1.Click

End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs)

End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'this

    AddHandler Button2.Click, AddressOf Button2_Click

    'now Button2_Click looks like this

    'Private Sub Button2_Click(ByVal sender As System.Object, _
    'ByVal e As System.EventArgs) Handles Button2.Click

End Sub
dbasnett
maybe. You only forgot the distructor behavior, where Handles will also remove the handler from the button.
serhio