#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();
        }
Advertisements

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.

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

  1. myspec says:

    I don’t fully understand why this EventHandler delegate types are recommended. Why we just can’t use delegates and benefit from their MultiCasting functionality, instead of declaring Events, which from my perspective are just plain wrappers for delegates…

    • Sean says:

      Yes, you’re right. You could add a member whose type is a delegate to the class and use it directly from the client code, adding and removing handler methods. So far, this is what the client code can do from an event. But if you use a delegate, the client code can also do additional things–like examining the invocation list and even setting the delegate instance to null. If what you really want as the author of a class is for clients to be able to subscribe to your events, then an event limits the client to this behavior. This is an example of encapsulaton–where you expose only the desired functionality to the client code and no more.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: