Search code examples
vb.nethandlesaddhandler

AddHandler vs. Handles - what is the difference?


I understood that Handles is only one way to add in constructor the AddHandler, but in general are these two are equivalent?


Solution

  • 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.