Why is this an issue?
It is possible to subscribe to events with anonymous delegates, but having done so, it is impossible to unsubscribe from them. That’s because the
process of subscribing adds the delegate to a list. The process of unsubscribing essentially says: remove this item from the subscription
list. But because an anonymous delegate was used in both cases, the unsubscribe attempt tries to remove a different item from the list than was added.
Instead, save the delegate to a variable and use the variable to subscribe and unsubscribe.
Noncompliant code example
listView.PreviewTextInput += (obj,args) =>
listView.PreviewTextInput -= (obj, args) =>
listView_PreviewTextInput(obj, args, listView); // Noncompliant; this delegate was never subscribed
EventHandler func = (obj,args) => listView_PreviewTextInput(obj,args,listView);
listView.PreviewTextInput += func;
listView.PreviewTextInput -= func;