Sunday, April 17, 2011

Removing EventHandler from itself

Lambda expression offers a great way to write less code for registering event handlers:

But what if we need to remove the event handler after the WriteLine call, from the event handler itself? It is possible, if the lambda expression delegate had a name:

One problem with this though, when initializing the handler variable, inside the code that initializes it, at the line button.Click -= handler we access the handler which at this point is not initialized yet! So, to fix this, simply initialize it with null first (which might look a little bit awkward):

No comments:

Post a Comment