Adding and Removing Anonymous Event Handler
There's an MSDN page that talks about this:
How to Subscribe to and Unsubscribe from Events
Note in particular:
If you will not have to unsubscribe to [sic] an event later, you can use the addition assignment operator (+=) to attach an anonymous method to the event.
And also:
It is important to notice that you cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, it is necessary to go back to the code where you subscribe to the event, store the anonymous method in a delegate variable, and then add the delegate to the event . In general, we recommend that you do not use anonymous functions to subscribe to events if you will have to unsubscribe from the event at some later point in your code.
For anyone interested, you can add and remove an anonymous event handler like this
public class Musician
{
public void TuneGuitar()
{
Metronome metronome = new Metronome();
EventHandler<EventArgs> handler = null;
handler = (sender, args) =>
{
// Tune guitar
// ...
// Unsubscribe from tick event when guitar sound is perfect
metronome.Tick -= handler;
};
// Attach event handler
metronome.Tick += handler;
}
}
public class Metronome
{
event EventHandler<EventArgs> Tick;
}
UPDATE:
In C# 7.0 we have supports for local functions so the TuneGuitar
method can now be written as:
public void TuneGuitar()
{
Metronome metronome = new Metronome();
void handler(object sender, EventArgs args)
{
// Tune guitar
// ...
// Unsubscribe from tick event when guitar sound is perfect
metronome.Tick -= handler;
};
// Attach event handler
metronome.Tick += handler;
}