#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: