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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: