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

#384 – The Difference Between Delegates and Events

Delegates are not the same thing as events in C#.

Delegates

  • A delegate type defines a signature for a method (number and type of parameters and return type)
  • A delegate instance is an instance of a delegate type that can refer to one or more methods
  • Can add/remove handlers using the +=, -= operators
  • Can invoke handlers by calling delegate instance like a method

Events

  • Is a class member representing something that the class might notify calling code about
  • Declared in the class like a field, whose type is a delegate type
  • Wraps a private member variable that is a delegate instance
  • Wraps private methods that add/remove methods to the delegate instance’s invocation list
  • Client code can add/remove handlers using the +=, -= operators
  • Client code can’t invoke directly

Basically, an event is a mechanism that uses a delegate to notify client code of something without exposing the delegate’s invocation list to the client.