Search code examples
c#.neteventsdelegatesanonymous-methods

How do I Unregister 'anonymous' event handler


Say if I listen for an event:

Subject.NewEvent += delegate(object sender, NewEventArgs e)
{
    //some code
}); 

Now how do I un-register this event? Or just allow the memory to leak?


Solution

  • If you need to unregister an event, I recommend avoiding anonymous delegates for the event handler.

    This is one case where assigning this to a local method is better - you can unsubscribe from the event cleanly.