For example, if these codes:
Button button1 = new Button();
// ...
button1.Click -= button1_Clicked;
are executed before:
button1.Click += button1_Clicked;
I found no error or exception, but I am wondering if there is any downside here.
If it is safe, why is it allowed to unsubscribe from an event that has never been subscribed?
You cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, go back to the code where you subscribe to the event, store the anonymous function in a delegate variable, and then add the delegate to the event.
Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.
In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place. An event is an action that takes place when a user interacts with a program.
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts.
I can't find a reference specific to events, but it is documented for the underlying function that events use, Delegate.Remove
:
Returns source if value is null or if the invocation list of value is not found within the invocation list of source
So it will be safe at least for events that use implicit accessors.
Custom accessors are a whole other ball of wax, as one could implement the remove
block however you want. I would assume people would mimic the implicit behavior, but this isn't enforced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With