views:

7834

answers:

4

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.

+1  A: 

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

class c1

{

event EventHandler someEvent;

ResetSubscriptions() {someEvent = null;}

}

Are you sure assigning null will clear the invocation list?
leppie
That is the behavior I am seeing. As I said in my question, I don't know if I'm overlooking something.
+2  A: 

You can achieve this by using the Delegate.Remove or Delegate.RemoveAll methods.

Micah
I don't believe this will work with lambda expressions or anonymous delegates.
+23  A: 

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.

Jon Skeet
Oh the wonders of object oriented programming.
Anders Rune Jensen
If you're stubborn, you can force it clear via reflection. See http://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control/91853#91853 .
Brian
@Brian: It depends on the implementation. If it's *just* a field-like event or an `EventHandlerList`, you may be able to. You'd have to recognise those two cases though - and there could be any number of other implementations.
Jon Skeet
A: 

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.

Jonathan C Dickinson