Search code examples
vb.nethandler

How to add an Action to an Event


I have an event in a generic class

Public class SomeClass
    Public Event ChangeEvent(oldValue As T, newValue As T)

    ' some code..
End Class

And I have a complicated method to which I pass an Action(Of T) which should get added to the event and later removed again. It would look something like the following:

Public Sub SomeSub(listener As Action(Of T, T)
    AddHandler ChangeEvent, listener
    ' some code
    RemoveHandler ChangeEvent, listener
End Sub

But on both lines the compiler gives me the following error:

Value of type 'Action(Of T, T)' cannot be converted to 'ChangeEventHandler'.

The following works, but I can't remove the handler as it was a lambda expression.

Public Sub SomeSub(listener As Action(Of T, T)
    AddHandler ChangeEvent, Sub(x, y) listener(x, y)
End Sub

Is there a solution which doesn't involve me storing the lambda as a member? Please note that I cannot change the Event. I am only in control of the Method adding the listener.


Solution

  • It is better if you explicitly declare your event handler delegate, rather than letting Visual Basic do it implicitly:

    Public Class SomeClass(Of T)
        Public Delegate Sub ChangeEventHandler(oldValue As T, newValue As T)
        Public Event ChangeEvent As ChangeEventHandler
    
        ' some code..
    End Class
    

    That way you can specify the delegate as a parameter of your method, thus giving the compiler the correct signature and you the ability to both add and remove it:

    Public Sub SomeSub(listener As ChangeEventHandler)
        AddHandler ChangeEvent, listener
        ' some code...
        RemoveHandler ChangeEvent, listener
    End Sub
    

    Now you and the compiler are both happy! :)