Wednesday, August 12, 2009

Trips&Ticks: Do you know how you can unsubscribe from anonymous method?

Anonymous Methods is a useful feature which we receive in Framework 2.0. It allows to easy pass a small code block as a delegate parameter (you can set a large block code but this code will be harmful because it is complex and isn't clear for perception). For example:
button1.Click += delegate
MessageBox.Show( "Anonymous" );
But I have one trouble. What can I do if I want to unsubscribe from event. Seems it is subscribed finally, isn't it?.. Noup! If we declare instance of delegate before define we can unsubscribe a event from this delegate in the code block. For example:
EventHandler handler = null;

handler = delegate
MessageBox.Show( "Anonymous" );
button2.Click -= handler;

button2.Click += handler;
So if we click on button1 we receive message box always. If we click on button2 we receive message box once.

1 comment:

Urs Enzler said...

Because we had this problem mostly in unit test scenarios, we implemented a EventTester component that takes care of registering and unregistering the event.
You can find this component in the library bbv.Common at

The usage is as follows:
using (new EventTester(testee, "MyEvent", expectedEventCalls))
// do some code
} // on dispose the event is unregistered and the call count is checked