Possible Duplicate:
Why must a lambda expression be cast when supplied as a plain Delegate parameter
Control.Invoke accepts a Delegate parameter type. I cannot pass a lamba expression as a Delegate without telling the compiler which type of delegate I’m passing.
textBox1.Invoke(() => { MessageBox.Show("Hello World"); }); //illegal
In this case, I can cast to Action
textBox1.Invoke((Action)(() => { MessageBox.Show("Hello World"); })); //legal
However, I can create a shorthand method via an extension method (I’ve seen Marc Gravell do this):
public static void Invoke(this Control control, Action action)
{
control.Invoke((Delegate)action);
}
Now my shorthand works…
textBox1.Invoke(() => { MessageBox.Show("Hello World"); }); //legal
How is it that the compiler can determine that an anonymous method is an Action in the extension method, but the compiler cannot determine a lamba is an Action and therefore a legal Delegate in the case of Control.Invoke?
First, the compiler is smart enough to determine that the parameter is of type
Action(as opposed to sayAction<T>). More importantly, the compiler can assume I mean anActionas opposed to anExpressionbecause the ambiguity is removed. If I do something silly to recreate ambiguity…say create an overload via a new extension method:The compiler will catch that as well:
The call is ambiguous between the following methods or properties:The comments made walked me to the answer I’m looking for.