#386 – Implementing a Static Event

You can implement static events in the same way that you implement normal (instance) events.  Like other static members, static events are associated with the class itself, rather than with an instance of the class.

An implementation of a static event (assumes existence of SomebodyBarkedEventArgs class):

        public static event EventHandler<SomebodyBarkedEventArgs> SomebodyBarked;

        // In instance method, raise the static event
        public void Bark(string barkSound)
        {
            Console.WriteLine("{0} says {1}", Name, barkSound);

            if (Dog.SomebodyBarked != null)
                Dog.SomebodyBarked(null, new SomebodyBarkedEventArgs(Name, barkSound));
        }

Adding an event handler for this event:

        static void Main()
        {
            // Tell me when any dog barks
            Dog.SomebodyBarked += new EventHandler<SomebodyBarkedEventArgs>(Dog_SomebodyBarked);

            Dog kirby = new Dog("Kirby");
            Dog jack = new Dog("Jack");

            // Pesky dogs bark
            jack.Bark("Grrrr");
            kirby.Bark("Woof");
        }

        static void Dog_SomebodyBarked(object sender, SomebodyBarkedEventArgs e)
        {
            Console.WriteLine("Dog {0} barked, saying {1}", e.DogName, e.Bark);
        }

Advertisements