Events can be static events or instance events. Static events are associated with the class as a whole, whereas instance events are associated with a specific instance of the class.
You can attach event handlers to both static and instance events.
// Add handler to static event
Dog.SomebodyBarked += new EventHandler<SomebodyBarkedEventArgs>(Dog_SomebodyBarked);
Dog kirby = new Dog("Kirby");
// Add handler to instance event
kirby.Barked += new EventHandler<SomebodyBarkedEventArgs>(kirby_Barked);
In both cases, we’re attaching a handler that is a static method.
static void Dog_SomebodyBarked(object sender, SomebodyBarkedEventArgs e)
{
Console.WriteLine("Dog {0} barked, saying {1}", e.DogName, e.Bark);
}
We can also attach a handler that is an instance method. So we can attach both static and instance methods as handlers, to either static or instance events.
For example:
BarkLogger log = new BarkLogger();
// Add instance method as handler for static event
Dog.SomebodyBarked += new EventHandler<SomebodyBarkedEventArgs>(log.LogBark);