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

            d.Bark();

            Console.ReadLine();
        }

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

1168-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Xavier Fischer says:

    Is there are way to unsubscribe to the event using the lambda syntax used.
    By the way, thanks for this blog, it is a great resource !

Leave a comment