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"; }
);

Which lead to this nice compiler error:

Cannot convert anonymous method block to
type 'System.Delegate' because it is not a delegate type

So now it’s telling me System.Delegate is not a delegate type… To the msdn library! Aha, just like the compiler said:

The Delegate class is not considered a delegate type; it is a class used to derive delegate types.

MethodInvoker is a delegate type however; and one I used to use a lot, so let’s cast the anonymous method block to that one…

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

Bingo, it worked!

I find this kinda confusing - I’d suspect that the compiler could see anonymous methods as delegate types without the need to cast them - not to mention that it looks ugly, and I wanted my code to be more readable.

Oh well, this’ll work too I guess :/