rspec/rules/S3244/rule.adoc
Arseniy Zaostrovnykh 7ca29f686f Force linebreaks
2021-02-02 15:02:10 +01:00

32 lines
1.0 KiB
Plaintext

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
----
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
----
EventHandler func = (obj,args) => listView_PreviewTextInput(obj,args,listView);
listView.PreviewTextInput += func;
// ...
listView.PreviewTextInput -= func;
----