Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a lambda expression a delegate?

Tags:

c#

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?

like image 256
P.Brian.Mackey Avatar asked Sep 05 '25 08:09

P.Brian.Mackey


2 Answers

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

form.Invoke(new Action(() => AMethod(form)));
like image 190
Justin Niessner Avatar answered Sep 07 '25 22:09

Justin Niessner


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.

like image 24
Servy Avatar answered Sep 07 '25 22:09

Servy