Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Possible Duplicates:
Unsubscribe anonymous method in C#
How do I Unregister ‘anonymous’ event handler

I recently discovered that I can use lambdas to create simple event handlers. I could for example subscribe to a click event like this:

button.Click += (s, e) => MessageBox.Show("Woho");

But how would you unsubscribe it?

share|improve this question
See here: stackoverflow.com/questions/183367 – Martin Harris Sep 1 '09 at 12:27
Have you tried the -= operator? – Maciek Sep 1 '09 at 12:27
1  
@Svish: A lambda is essentially an anonymous method. – dtb Sep 1 '09 at 12:30
Aha, so that would be a yes then. – Svish Sep 1 '09 at 12:32
Unless I'm missing a subtle difference, your question is answered here: stackoverflow.com/questions/805829/…, though its accepted answer is wrong (but corrected in a comment). – Jeff Sternal Sep 1 '09 at 12:41
show 2 more comments

marked as duplicate by Martin Harris, Andrew Hare, dtb, Svish, John Saunders Sep 3 '09 at 4:23

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer

up vote 79 down vote accepted

The C# specification explicitly states (IIRC) that if you have two anonymous functions (anonymous methods or lambda expressions) it may or may not create equal delegates from that code. (Two delegates are equal if they have equal targets and refer to the same methods.)

To be sure, you'd need to remember the delegate instance you used:

EventHandler handler = (s, e) => MessageBox.Show("Woho");

button.Click += handler;
...
button.Click -= handler;

(I can't find the relevant bit of the spec, but I'd be quite surprised to see the C# compiler aggressively try to create equal delegates. It would certainly be unwise to rely on it.)

If you don't want to do that, you'll need to extract a method:

public void ShowWoho(object sender, EventArgs e)
{
     MessageBox.Show("Woho");
}

...

button.Click += ShowWoho;
...
button.Click -= ShowWoho;
share|improve this answer
This works. I have tried it! – awe Sep 1 '09 at 12:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.