When working with anonymous
functions, it is important to keep in mind that each time you create one, it is a completely new instance.
In this example, even though the same lambda expression is used, the expressions are stored separately in the memory and are therefore not equal or
the same.
Func<int, int> lambda1 = x => x + 1;
Func<int, int> lambda2 = x => x + 1;
var result = lambda1 == lambda2; // result is false here
This is even more true when working with events since they
are multicast
delegates that offer ways of subscribing and
unsubscribing to them. If an anonymous function is used to subscribe to an event, it is impossible to unsubscribe from it. This happens because to
remove the entry from the subscription list, a reference to the original method is needed, but if the anonymous function has not been stored before
subscribing, there is no way to find a reference to it.
Instead, store the callback to a variable or a named method and use the variable or method to subscribe and unsubscribe.