I think anonymous methods are a great feature, and I use them where I can to improve code readability. I thought they would be especially useful in Windows Forms controls, if you want to execute a small piece of code on the UI thread using the Control.Invoke method.

The Control.Invoke method takes a Delegate parameter, so I figured I could just do something like:

this.Invoke(
    delegate { this.Text = "x"; }
);

Well, I was wrong, it seems that a conversion from an anonymous method (a delegate) to a Delegate is not something trivial and I got this compiler error:

Argument '1': cannot convert from
'anonymous method' to 'System.Delegate'

So, I tried to help a bit by explicitly casting the thing…

this.Invoke(
    (Delegate) delegate { this.Text = "x"; }
);

Continue Reading »