How can I raise an event from another class which implements an interface that contains an event?
Public Interface IMyEvent
Event MyEvent()
End Interface
Public Class ClassA
Implements IMyEvent
Public Event MyEvent() Implements IMyEvent.MyEvent
End Class
Public Class ClassB
Public myClassA As New ClassA
Public Sub New()
Dim myIEvent As IMyEvent = CType(myClassA, IMyEvent)
RaiseEvent myIEvent.MyEvent ' Doesn't work.
End Sub
End Class
Note the comment – that code doesn’t work. How can I raise an event like this, if it’s contained within another class through an interface?
First, the reason you can’t do this is because
events can only be called on the class in which they are declared.The usual way around this is to provide a
protectedOnEventName()method, which invokes the event. Then, you can inherit from the class and either call or override theOnEventName()method to invoke the event. If you really want to be able to do this from a class that is unrelated in the hierarchy, you can add theOnEventName()method to the interface you declared.