Monday, June 27, 2011

How to unsubscribe from an Event which is registered to an anonymous method

Anyone who has been doing any type of .net development knows you can subscribe (MSDN on event subscription) to an event as follows:
Subscribe to an Non-Anonymous Method

...
// instance class w/ an event
myClass.DoSomething += HandleDoSomething
...
// the method which handles the event
privat evoid HandleDoSomething( object s, args e )
{

// Logic goes here
}
Subscribe to an Anonymous Method
...
// instance class w/ an event
myClass.DoSomething += (s, e) => {
         // logic goes here
    }
And to unsubscribe from a non-anonymous method you would do the following
...
// instance class w/ an event
myClass.DoSomething -= HandleDoSomething
...


Read more: Derik Whittaker
QR: how-to-unsubscribe-from-an-event-which-is-registered-to-an-anonymous-method.aspx