rspec/rules/S3244/rule.adoc

34 lines
1.1 KiB
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +01:00
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++``.
2020-06-30 12:48:39 +02:00
2021-02-02 15:02:10 +01:00
2020-06-30 12:48:39 +02:00
Instead, save the delegate to a variable and use the variable to subscribe and unsubscribe.
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:48:39 +02:00
----
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
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:48:39 +02:00
----
EventHandler func = (obj,args) => listView_PreviewTextInput(obj,args,listView);
listView.PreviewTextInput += func;
// ...
listView.PreviewTextInput -= func;
----