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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
(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:
If you want to create an event handler which removes itself using a lambda expression, it’s slightly trickier – you need to refer to the delegate within the lambda expression itself, and you can’t do that with a simple “declare a local variable and assign to it using a lambda expression” because then the variable isn’t definitely assigned. You typically get around this by assigning a null value to the variable first:
Unfortunately it’s not even easy to encapsulate this into a method, because events aren’t cleanly represented. The closest you could come would be something like:
Even that would be tricky to implement within
Delegates.AutoUnsubscribebecause you’d have to create a newEventHandler(which would be just a generic type argument). Doable, but messy.