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

Viewed 68310

Take the method System.Windows.Forms.Control.Invoke(Delegate method)

Why does this give a compile time error:

string str = "woop";
Invoke(() => this.Text = str);
// Error: Cannot convert lambda expression to type 'System.Delegate'
// because it is not a delegate type

Yet this works fine:

string str = "woop";
Invoke((Action)(() => this.Text = str));

When the method expects a plain Delegate?

9 Answers

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

Tired of casting lambdas over and over?

public sealed class Lambda<T>
{
    public static Func<T, T> Cast = x => x;
}

public class Example
{
    public void Run()
    {
        // Declare
        var c = Lambda<Func<int, string>>.Cast;
        // Use
        var f1 = c(x => x.ToString());
        var f2 = c(x => "Hello!");
        var f3 = c(x => (x + x).ToString());
    }
}

Playing with XUnit and Fluent Assertions it was possible to use this inline capability in a way I find really cool.

Before

[Fact]
public void Pass_Open_Connection_Without_Provider()
{
    Action action = () => {
        using (var c = DbProviderFactories.GetFactory("MySql.Data.MySqlClient").CreateConnection())
        {
            c.ConnectionString = "<xxx>";
            c.Open();
        }
    };

    action.Should().Throw<Exception>().WithMessage("xxx");
}

After

[Fact]
public void Pass_Open_Connection_Without_Provider()
{
    ((Action)(() => {
        using (var c = DbProviderFactories.GetFactory("<provider>").CreateConnection())
        {
            c.ConnectionString = "<connection>";
            c.Open();
        }
    })).Should().Throw<Exception>().WithMessage("Unable to find the requested .Net Framework Data Provider.  It may not be installed.");
}

Other answers were correct at the time they were written, but starting from C# 10.0 (from 2021), the compiler can infer a suitable delegate type (like some Func<...>, Action<...> or generated delegate type) in such cases.

See C# 10 Features - Lambda improvements.

string str = "woop";
Invoke(() => this.Text = str);   // OK in C# 10.0, in this case 'Func<string>' is picked
string str = "woop";
Invoke(() => { this.Text = str; });   // OK in C# 10.0, in this case 'Action' is picked

Comments assume the signature Invoke(Delegate method) as in your question. Of course if the method wants a particular (not abstract) delegate type, C# will attempt to convert the lambda into that one, as was also the case before C# 10.0.

Related