#387 – Static Events vs. Static Event Handler Methods

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

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 )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: