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
?