#390 – Using the Same Handler for Multiple Events

You can attach a single event handler (method) to more than one event, originating from more than one object.

In the example below, we have a general DogMadeSound handler that we attach to the Barked and Growled events of one Dog instance (Kirby) and to the Barked event of another Dog (Jack).  When any of these events fire, our handler will get called.

        static void Main()
            Dog kirby = new Dog("Kirby");
            Dog jack = new Dog("Jack");

            // We handle Kirby's barks and growls and Jack's barks
            kirby.Barked += new EventHandler<DogEventArgs>(DogMadeSound);
            kirby.Growled += new EventHandler<DogEventArgs>(DogMadeSound);
            jack.Barked += new EventHandler<DogEventArgs>(DogMadeSound);


        static void DogMadeSound(object sender, DogEventArgs e)
            Console.WriteLine("DogMadeSound handler: {0} - {1}", e.DogName, e.Sound);


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 )

Connecting to %s

%d bloggers like this: