#379 – Using the EventHandler Delegate for Events that Return No Data

When you add an event to a class, you can use any delegate you like for the event’s type.  For example, you could based the event on a delegate that accepts a single parameter of type string:

        public delegate void StringHandlerDelegate(string s);
        public event StringHandlerDelegate Barked;

It’s recommended, however, that you use the one of the following two preexisting types as the delegate type:

  • EventHandler – for event that return no data
  • EventHandler<TEventArgs> – for event that returns some data

Below is an example of an event that returns no data.  The Dog.Barked event is raised when a Dog object barks.

        // Declare the event
        public event EventHandler Barked;

        // Helper method that raises the event
        protected virtual void OnBarked()
        {
            if (Barked != null)
                Barked(this, null);
        }

        // In Bark method, call helper to raise the event
        public void Bark()
        {
            Bark("Woof");
            OnBarked();
        }

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers