Why must a lambda expression be cast when supplied as a plain Delegate parameter

A lambda expression can either be converted to a delegate type or an expression tree – but it has to know which delegate type. Just knowing the signature isn’t enough. For instance, suppose I have:

public delegate void Action1();
public delegate void Action2();

...

Delegate x = () => Console.WriteLine("hi");

What would you expect the concrete type of the object referred to by x to be? Yes, the compiler could generate a new delegate type with an appropriate signature, but that’s rarely useful and you end up with less opportunity for error checking.

If you want to make it easy to call Control.Invoke with an Action the easiest thing to do is add an extension method to Control:

public static void Invoke(this Control control, Action action)
{
    control.Invoke((Delegate) action);
}

Leave a Comment