HOW TO: Use Events From An Inherited Class

When designing objects I will always think that not only will I be coding functionality in the object, but potentially someone else could be extending this functionality.  Almost every time I have written an object I have come back to it to expand it out to help usability.  One big subject that I have struggled a little with is how to expose events to descendant classes.  This becomes a point of focus when working in an Agile environment, because the requirements can shift and change and you want to be able to shift and change with them.  Designing a base class like a persistent Person object requires that you release as much control to the descendant while protecting any logic that is completely necessary.

Let’s take the following example of a person that notifies applications when today is their birthday:

VB.NET

Public Class Person

    Public BirthDate As Date
    Public Sub DateChanged(ByVal NewDate As Date)
        If NewDate = BirthDate Then
            RaiseEvent ItsMyBirthday()
        End If
    End Sub
    Public Event ItsMyBirthday()
End Class

C#

    public class Person
    {
        public DateTime BirthDate;
        public void DateChanged(DateTime NewDate)
        {
            if (NewDate == BirthDate)
                ItsMyBirthday(this,new EventArgs());
        }
        public event EventHandler ItsMyBirthday;
    }

You cannot implicitly call RaiseEvent for a base class event, so to work around this issue we create a method in the base that as always should be overridable.  Typically I will call this On<EventName>.  In this case I would call it OnBirthday and have the base method raise the event.  This change would look something like this:

VB.NET

    Public Overridable Sub OnBirthday()
        RaiseEvent ItsMyBirthday()
    End Sub

C#

    public void OnBirthday()
    {
        ItsMyBirthday(this, new EventArgs());
    }

Now you can call OnBirthday in your base class if you wanted to have two birthdays and inform your application of such.  Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>