#1,170 – You Can’t Unsubscribe from an Event Using a Lambda Expression

Suppose that you subscribe to an event using a lambda expression:

            Dog d = new Dog("Bowser");

            // NOTE: Barked is EventHandler<string>
            d.Barked += (s, e) => Console.WriteLine("Bark: {0}", e);

You cannot, however, unsubscribe using the same syntax. The -= operator shown below will be using a different anonymous method, so the original will not be removed from the event’s invocation list.

            // Not what you expect
            d.Barked -= (s, e) => Console.WriteLine("Bark: {0}", e); 

So the lambda expression syntax is fine–as long as you don’t need to unsubscribe from the event.  (More on that in a future post).

If you want to unsubscribe, but still use lambda syntax, you could persist the delegate instance.

            EventHandler<string> handler = (s, e) => Console.WriteLine("Bark: {0}", e);
            d.Barked += handler;

            // ...

            d.Barked -= handler;

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

Leave a comment