Expression Lambda versus Statement Lambda

Reflector to the rescue! The disassembled code looks like this:

private static void Main(string[] args)
{
    MyDelegate myDelegate1 = delegate {
        Console.WriteLine("Test 1");
    };
    MyDelegate myDelegate2 = delegate {
        Console.WriteLine("Test 2");
    };
    myDelegate1();
    myDelegate2();
    Console.ReadKey();
}

So no, there is no real difference between the two. Be happy.


You need statement lambda for multistatement lambdas. In addition statement lambdas are not supported by expression providers like LINQ to SQL. Before .NET 4.0 the .NET Framework did not have support for statement expression trees. This was added in 4.0 but as far as I know no provider uses it.

Action myDelegate1 = () => Console.WriteLine("Test 1");
Expression<Action> myExpression = () => { Console.WriteLine("Test 2") }; //compile error unless you remove the { }
myDelegate1();
Action myDelegate2 = myExpression.Compile();
myDelegate2();

Otherwise they are the same.

Tags:

C#

Lambda