tags:

views:

67

answers:

4

Is it possible to instead of doing this:

person.Walking -= person_Walking1;
person.Walking -= person_Walking2;
person.Walking -= person_Walking3;

Do this:

person.Walking = // remove all the handlers without knowing their names

Thanks.

+1  A: 

Sure. Just set:

person.Walking = null;
Dan Story
That's assuming you're writing code within the class publishing the event.
Jon Skeet
Quite true. I should have clarified that it's an internal ability only.
Dan Story
+4  A: 

No. Part of the point of events is that they prevent you from doing that. If I've subscribed to a button click and you've subscribed to a button click, what right have you to remove my handler? (Okay, that's anthropomorphising somewhat, but you get the idea.) Note that it's not a matter of knowing the "name" of an event handler - you have to be able to provide a reference to an "equal" delegate instance.

For example, if you subscribe to an event using an anonymous method or a lambda expression, you'll have to keep a reference to that somewhere:

EventHandler handler = (sender, args) => Console.WriteLine("Clicked!");
button.Click += handler;
...
button.Click -= handler;

When you use the name of a method, that's performing a method group conversion from the name of the method to a delegate instance:

button.Click += HandleEvent;
...
button.Click -= HandleEvent;

Here there are two separate delegate instances involved, but they're equal as they have the same invocation list (they do the same thing) and they have the same target (they're doing that thing "on" the same object).

EDIT: I'm assuming you only have access to it as an event, not as a field - if you're writing code in the class which publishes the event, you can do what you like, and setting the field to null (or removing it from the collection, or however your implementation works) is fine.

Jon Skeet
Yeah, the access is an event. I guess I'll have to find a different solution.
Carlo
No one better mess with Jon Skeet's event handlers!
Pierreten
I like this solution, but it's not feasible at this point of the project, there's a ton of places where we're trying to do that, and implementing this and testing would be too time consuming. That's why I wanted something as easy as clearing all the events in one line.
Carlo
A: 

Not from outside the class in which the events are defined. If you really wanted to, you could define a method like this:

public void ClearEventListeners() {
    MyEvent.Clear();
}

(The exact call may be different, if it exists, but IntelliSense should point you in the right direction.)

Lucas Jones
I already tried this but it doesn't work in this case, since not even that class with the events has access to those handlers. Thanks.
Carlo
It was worth a shot! :)
Lucas Jones
+1  A: 

This is one of the reasons events were invented. If you wanted to do something like that, use delegates.

Raj Kaimal