Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to unsubscribe from an event that has never been subscribed?

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?

like image 655
Setyo N Avatar asked Sep 05 '14 03:09

Setyo N


People also ask

Is it possible to unsubscribe from events?

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.

How do I unsubscribe from an event listener?

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.

What is event Handler?

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.

What is event in C# with example?

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.


1 Answers

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.

like image 117
Cory Nelson Avatar answered Sep 19 '22 15:09

Cory Nelson