VB.NET: Raise base class events from a derived class

Say we:

  1. Have a class we want to divide into subclasses
  2. The future base class has events
  3. 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

Comments

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

    did you run into that issue?

    ReplyDelete
    Replies
    1. 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

Post a Comment

Popular posts from this blog

C++/CLI: Convert a String to BSTR or some other nasty stuff

Upgrading Lodash from 3.x to 4.x