P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

Is a lambda expression a delegate?

I can't directly pass a lambda

form.Invoke(() => AMethod(form));

Because oddly enough a lambda is not a delegate type (per the compiler error). I seem to recall different information in Jon Skeet's .NET 4.0 book. And on MSDN it says:

A lambda expression is an anonymous function that you can use to create delegates or expression tree types

    public static void Main()
    {
        Form form = new Form();                                
        form.Show();
        form.Invoke(() => AMethod(form));
        Application.Run();

        Console.Read();
    }

    public static void AMethod(Form form)
    {
        form.SendToBack();
    }
}

Yet, here we receive a compiler error:

Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type.

Lambda's are supposed to be syntactic sugar for anonymous delegates. So what is the story here? What have I missed?

Upvotes: 4

Views: 556

Answers (3)

Tomino
Tomino

Reputation: 6249

Try to create Action: form.Invoke(new Action(() => MyMethod(form)));

Upvotes: 0

Servy
Servy

Reputation: 203802

Yes, lambdas are used to create delegates, but they are not themselves delegates. The primary issue here is that lambdas don't have a signature, their parameter list and return type are determined based on the context they are placed in. When you place a lambda somewhere where a particular defined delegate instance is expected then the compiler knows what signature the lambda must match to be valid.

Invoke on the other hand doesn't take some particular delegate type, it takes an instance of Delegate which doesn't have any signature. You need to wrap your lambda in new SomeActualDelegateType(...) (Action is a common choice for some delegate here, but not the only choice) to give it an actual signature.

Upvotes: 5

Justin Niessner
Justin Niessner

Reputation: 245389

Lambda's themselves are not delegates. But, like your quoted text, they can be used to create delegates:

form.Invoke(new Action(() => AMethod(form)));

Upvotes: 6

Related Questions