#1,168 – Using a Lambda Expression as an Event Handler

You can use a lambda expression wherever a delegate instance is expected.  This includes using a lambda expression when defining an event handler.

        static void Main(string[] args)
            Dog d = new Dog("Bowser");

            // Method #1 - Subscribe to Barked event using named method
            d.Barked += d_Barked;

            // Method #2 - Subscribe to Barked event using lambda expression
            d.Barked += (s, e) => { Console.WriteLine("My dog says {0}", e); };



        static void d_Barked(object sender, string e)
            Console.WriteLine("Dog {0} just barked, saying {1}",
                ((Dog)sender).Name, e);



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



        // Neither argument is used, for the moment
        static void kirby_Barked(object sender, EventArgs e)
            // Log Kirby's barks

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

#368 – How Events Work

An event in C# is a mechanism that allows an object to inform client code about something that happened inside the object that the other code might care about.

For example, you might have a Dog object that raises a Barked event whenever someone calls the dog’s Bark method.  Your code can be notified whenever the dog barks.

In .NET, we say that the Dog object raises the Barked eventThe logging code handles the Barked event in a method known as an event handler.

Events in C# implement something known as the Publish/Subscribe pattern.  The Dog class publishes information about when the dog barks and the logging code subscribes to that information. 

This is also known as the Observer pattern.  The logging code observes the Dog object and the Dog object notifies any observers whenever the dog barks.