#380 – Handling Events that Use the EventHandler Delegate Type

Events that return no event data should normally use the built-in EventHandler delegate type.

        public event EventHandler Barked;

EventHandler is a delegate that takes two parameters.

public delegate void EventHandler(object o, EventArgs e);

The first parameter is assumed to be a reference to the object that raised the event.  The second parameter will contain a reference to some subclass of the EventArgs class, if the event does return data, or will be a null value, if the event does not pass data back.

Here’s an example of subscribing to the Barked event defined above.

            // Subscribing to the event
            Dog kirby = new Dog("Kirby");
            kirby.Barked += kirby_Barked;

            kirby.Bark();

And an example of a handler for the Barked event.

        static void kirby_Barked(object o, EventArgs e)
        {
            Console.WriteLine("Kirby barked");
        }
Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

%d bloggers like this: