#382 – Handling an Event that Returns Some Data

When you implement an event that returns data, you can use the EventHandler<TEventArgs> delegate type.

When you use the EventHandler<TEventArgs> delegate type, you define a new class that inherits from EventArgs.  A client that wants to handle the new event will need access to this new class.

Suppose that a Dog class implements a Barked event that has the following signature:

        public event EventHandler<BarkedEventArgs> Barked;

You would then add an event handler that accepts two parameters:

  • Parameter of type object, which references the object that raised the event
  • Parameter of type BarkedEventArgs, which contains the data the event wants to pass back

Here’s the complete example:

        static void Main()
            Dog kirby = new Dog("Kirby");
            kirby.Barked += kirby_Barked;


        // Handle the Barked event
        static void kirby_Barked(object o, BarkedEventArgs e)
            Console.WriteLine("Kirby barked: {0}", e.BarkSound);

#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)