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

            kirby.Bark("Grrr");
        }

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

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

Leave a comment