VB.NET: Raise base class events from a derived class
Say we:
- Have a class we want to divide into subclasses
- The future base class has events
- The refactoring leads us to the need of raising an event declared in the base class, from a derived class.
When we try to do point 3, we will get a compile error saying that a derived class cannot raise events from a base class. To get around this, we add a protected method in the base class which encapsulates the RaiseEvent call, and call that method from the derived class using MyBase. This way:
In the base class (parameters as needed):Protected Overridable Sub OnMessageGenerated(ByVal NewSender As Object, ByVal NewMessage As String)
RaiseEvent MessageGenerated(NewSender, New MessageEventArgs(NewMessage))
End Sub
And in the derived class:
'Do stuff
'Raise base class event
MyBase.OnMessageGenerated( Me, "Message" )
'Do more stuff...
References:
Mark Gilbert post
I am not seeing how the calling code can work with this. I was following the same approach and in my calling code, the subclass does not expose any events so you cant have a sub that handles that event
ReplyDeletedid you run into that issue?
There is no need for the subclass to expose events; you just call the protected sub when you want to fire the base class' event.
Delete