rspec/rules/S3244/rule.adoc

36 lines
1.1 KiB
Plaintext

== 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. The result: ``++NOOP++``.
Instead, save the delegate to a variable and use the variable to subscribe and unsubscribe.
=== Noncompliant code example
[source,text]
----
listView.PreviewTextInput += (obj,args) =>
listView_PreviewTextInput(obj,args,listView);
// ...
listView.PreviewTextInput -= (obj, args) =>
listView_PreviewTextInput(obj, args, listView); // Noncompliant; this delegate was never subscribed
----
=== Compliant solution
[source,text]
----
EventHandler func = (obj,args) => listView_PreviewTextInput(obj,args,listView);
listView.PreviewTextInput += func;
// ...
listView.PreviewTextInput -= func;
----