#393 – Implement a Helper Method to Raise an Event

You typically raise an event from within a class by first checking to see if the event is null, i.e. if there are any handlers defined for the event.

        public void Bark(string barkSound)
        {
            Console.WriteLine("{0} says {1}", Name, barkSound);

            if (Barked != null)
                Barked(this, new BarkEventArgs(Name, barkSound));
        }

It’s common practice, however, to define a helper method in your class that actually raises the event.  This method encapsulates the logic of raising the event, including the check for null.  If you also define this method as protected virtual, future subclasses of your class can override the helper method to override the behavior of raising the event.

        public void Bark(string barkSound)
        {
            Console.WriteLine("{0} says {1}", Name, barkSound);
            OnBarked(barkSound);
        }

        protected virtual void OnBarked(string barkSound)
        {
            if (Barked != null)
                Barked(this, new BarkEventArgs(Name, barkSound));
        }
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: