#390 – Using the Same Handler for Multiple Events
August 16, 2011 Leave a comment
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); kirby.Bark("Woof"); kirby.Growl(); jack.Bark("Yap"); } static void DogMadeSound(object sender, DogEventArgs e) { Console.WriteLine("DogMadeSound handler: {0} - {1}", e.DogName, e.Sound); }