How do I Unregister 'anonymous' event handler

P.K picture P.K · Aug 28, 2009 · Viewed 21.4k times · Source

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?

Answer

dtb picture dtb · Aug 28, 2009

Give your instance of the anonymous delegate a name:

EventHandler<NewEventArg> handler = delegate(object sender, NewEventArgs e)
{
    //some code
};

Subject.NewEvent += handler;
Subject.NewEvent -= handler;