#381 – Implementing an Event that Returns Some Data

When you implement an event, you can define your own delegate type, or you can use the existing EventHandler or EventHandler<TEventArgs> types.

If you want your event to return some data, you should:

  • Create a new class that inherits from EventArgs for the event’s data
  • Use the EventHandler<TEventArgs> delegate type

Start by defining new EventArgs-based class that will store the event’s data.

    public class BarkedEventArgs : EventArgs
        public string BarkSound { get; protected set; }
        public BarkedEventArgs(string barkSound)
            BarkSound = barkSound;

Then, in your class, declare the event and a helper method to raise the event.

        // Declare the event
        public event EventHandler<BarkedEventArgs> Barked;

        // Helper method that raises the event
        protected virtual void OnBarked(string sound)
            if (Barked != null)
                Barked(this, new BarkedEventArgs(sound));

Finally, raise the event whenever a Dog barks.

        public void Bark(string barkSound)


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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: