Peter Long
Peter Long

Reputation: 4022

lambda -> delegate doesn't compile

The last statement does not compile. please refer to the comments along with the code for the detail of my question.

class Test
{
    private static void Foo(Delegate d){}

    private static void Bar(Action a){}

    static void Main()
    {
        Foo(new Action(() => { Console.WriteLine("a"); })); // Action converts to Delegate implicitly

        Bar(() => { Console.WriteLine("b"); }); // lambda converts to Action implicitly

        Foo(() => { Console.WriteLine("c"); }); // Why doesn't this compile ? (lambda converts to Action implicitly, and then Action converts to Delegate implicitly)
    }
}

Upvotes: 2

Views: 260

Answers (2)

Peter K.
Peter K.

Reputation: 8108

Why should the compiler know how to two-step: from lambda -> Action -> Delegate?

This compiles:

class Test
{
    private static void Foo(Delegate d) { }

    private static void Bar(Action a) { }

    static void Main()
    {
        Foo(new Action(() => { Console.WriteLine("world2"); })); // Action converts to Delegate implicitly

        Bar(() => { Console.WriteLine("world3"); }); // lambda converts to Action implicitly

        Foo((Action)(() => { Console.WriteLine("world3"); })); // This compiles
    }
}

Upvotes: 1

Chris Shain
Chris Shain

Reputation: 51359

Because the .net compiler doesn't know what type of delegate to turn the lambda into. It could be an Action, or it could be a void MyDelegate().

If you change it as follows, it should work:

Foo(new Action(() => { Console.WriteLine("c"); }));

Upvotes: 4

Related Questions