How can I clear event subscriptions in C#?


Take the following C# class:

c1 {
 event EventHandler someEvent;

If there are a lot of subscriptions to c1's someEvent event and I want to clear them all, what is the best way to achieve this? Also consider that subscriptions to this event could be/are lambdas/anonymous delegates.

Currently my solution is to add a ResetSubscriptions() method to c1 that sets someEvent to null. I don't know if this has any unseen consequences.

11/1/2011 2:43:39 PM

Accepted Answer

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.

10/9/2012 10:44:32 PM

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow