#1,168 – Using a Lambda Expression as an Event Handler
August 26, 2014 2 Comments
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); }
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 !
Excellent question! I’ll answer that one in an upcoming post.