Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Events in Base Classes

Ok, so I have a base class which declares the event StatusTextChanged. My child class, of course cannot directly raise this event.

So I wind up with something like this (for simplicity sake):

Public MustInherit Class FooBase
    Public Event StatusTextChanged(ByVal StatusText As String)
    Protected Sub RaiseStatusTextChangedEvent(ByVal StatusText As String)
        RaiseEvent StatusTextChanged(StatusText)
    End Sub
End Class

And then in the child class I call MyBase.RaiseStatusTextChangedEvent("something"). Is there a better or more recommended way to do this?

edit: VB.NET or C#, either way it works essentially the same.

edit: So after the responses, I'm at this in the base class, then just set the StatusText property in the child class ...

    Public Event StatusTextChanged(ByVal StatusText As String)
    Private _StatusText As String = "Idle."
    Public Property StatusText() As String
        Get
            Return _StatusText
        End Get
        Protected Set(ByVal value As String)
            RaiseEvent StatusTextChanged(value)
        End Set
    End Property
like image 344
hmcclungiii Avatar asked Mar 01 '26 03:03

hmcclungiii


2 Answers

I would say that you are rather close to the recommeneded way (or at least the one I would recommend).

I would make a few alterations to your code, given a choice:

  • Make StatusTextChanged Protected Overridable
  • Wrap StatusText in a custom EventArgs class
  • Change the StatusTextChanged declaration into Public Event StatusTextChanged As EventHandler(Of YourCustomEventArgs)

The resulting code:

The custom eventargs class:

Public Class TextEventArgs
    Inherits EventArgs

    Private _text As String

    Public Sub New(ByVal text As String)
        _text = text
    End Sub

    Public ReadOnly Property Text() As String
        Get
            Return _text
        End Get
    End Property

End Class

The event implementation in your base class:

Public Event StatusTextChanged As EventHandler(Of TextEventArgs)
Protected Overridable Sub OnStatusTextChanged(ByVal e As TextEventArgs)
    RaiseEvent StatusTextChanged(Me, e)
End Sub

...and finally a code line for raising the event; either in the base class or a class that inherits it:

OnStatusTextChanged(New TextEventArgs("some text"))

This will be more in line with how events are designed within the rest of the .NET framework.

like image 127
Fredrik Mörk Avatar answered Mar 03 '26 22:03

Fredrik Mörk


Unless there is a specific need for your child class to override a base class method then I would say that calling the base class implementation is absolutely the best solution.

like image 26
Lazarus Avatar answered Mar 03 '26 23:03

Lazarus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!