#370 – Subscribe to an Event by Adding an Event Handler

You subscribe to a particular event in C# by defining an event handler–code that will be called whenever the event occurs (is raised). You then attach your event handler to an event on a specific object, using the += operator.

Below is an example where we define an event handler for the Dog.Barked event.  Each time that Kirby barks, we’ll record the date and time of the bark in a list.

        private static List<DateTime> barkLog = new List<DateTime>();

        static void Main()
        {
            Dog kirby = new Dog("Kirby", 12);

            kirby.Barked += new EventHandler(kirby_Barked);

            kirby.Bark();
            Console.ReadLine();

            kirby.Bark();
            Console.ReadLine();
        }

        // Neither argument is used, for the moment
        static void kirby_Barked(object sender, EventArgs e)
        {
            // Log Kirby's barks
            barkLog.Add(DateTime.Now);
        }

Assuming that the Dog class fires its Barked event whenever we call the Bark method, our handler will get called whenever Kirby barks.

Advertisements