Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear event subscriptions in C#?

People also ask

How to unsubscribe from event c#?

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.


From within the class, you can set the (hidden) variable to null. A null reference is the canonical way of representing an empty invocation list, effectively.

From outside the class, you can't do this - events basically expose "subscribe" and "unsubscribe" and that's it.

It's worth being aware of what field-like events are actually doing - they're creating a variable and an event at the same time. Within the class, you end up referencing the variable. From outside, you reference the event.

See my article on events and delegates for more information.


Add a method to c1 that will set 'someEvent' to null.

public class c1
{
    event EventHandler someEvent;
    public ResetSubscriptions() => someEvent = null;    
}

class c1
{
    event EventHandler someEvent;
    ResetSubscriptions() => someEvent = delegate { };
}

It is better to use delegate { } than null to avoid the null ref exception.


Setting the event to null inside the class works. When you dispose a class you should always set the event to null, the GC has problems with events and may not clean up the disposed class if it has dangling events.