unhooking events

  • Thread starter Thread starter John
  • Start date Start date
J

John

Hi,

Does anyone know a way that I can unhook an event without
passing the original event handler ?

i.e I want to do like this:

foreach(eventhandler in object.SomethingChanged)
{
object.SomethingChanged -= SomethingChanged(abc);
}

John
 
You should be able to do this:

event EventHandler myEvent;

adding:
myEvent += new EventHandler(mymethod);

removing:
myEvent -= new EventHandler(mymethod);


I guess the theory is that the underlying delegate list is using the Equals
method on the delegate object, which must be comparing the values of the
delegate object instead of object identity. Thus you are not required to the
original EventHandler object that you added.


Hope this helps

Thomas
 
Will this work if I have alot of objects hooked to the
same event?

PS. I am doing this in a different class to where the
delegate is
 
It should work.

The notation is used is a bit compact so it may be misleading. Here's the
code in more detail:

class EventProducer {
private EventHandler _holaEH;
public event EventHandler Hola {
add {_holaEH+=value;}
remove {_holaEH-=value;}
}
}


class SomeEventListener {
private void HolaWasFired(object source, EventArgs args) {
... do something with the event
}

...... inside some method that handles attachment to the Hola event
EventProducer ep = ....
// Attach Hola event to the HolaWasFired method
ep.Hola += new EventHandler(HolaWasFired);


...... inside some method that handles detachment from the Hola event
EventProducer ep = ....
// Remove the HolaWasFired method from the Hola event
// This will remove the method attached above.
ep.Hola -= new EventHandler(HolaWasFired);

}
 
Back
Top