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):

Monday, April 11, 2011

Managed GetLastError

When p/invoking a native method from managed code, it's not ok to call GetLastError to check for an error, because internally the .Net engine can call other API native methods who might override the last error you actually want from the method you invoke. The solutions is Marshall.GetLastWin32Error.