Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression Lambda versus Statement Lambda

Tags:

c#

lambda

Fundamentally, is there any difference between a single-line expression lambda and a statement lambda? Take the following code, for example:

private delegate void MyDelegate();

protected static void Main()
{
    MyDelegate myDelegate1 = () => Console.WriteLine("Test 1");
    MyDelegate myDelegate2 = () => { Console.WriteLine("Test 2"); };

    myDelegate1();
    myDelegate2();

    Console.ReadKey();
}

While I prefer the first because I find the brackets to be ugly, is there anything different between the two (besides the obvious part about requiring brackets for multi-line statements)?

like image 248
senfo Avatar asked Mar 09 '12 15:03

senfo


People also ask

What is the difference between a lambda expression and a method?

Lambda expression is an anonymous method (method without a name) that has used to provide the inline implementation of a method defined by the functional interface while a method reference is similar to a lambda expression that refers a method without executing it.

Can lambda expressions contain statements?

In particular, a lambda function has the following characteristics: It can only contain expressions and can't include statements in its body. It is written as a single line of execution.

Why are lambda expressions called lambda?

They're being added in as part of Project Lambda. But what is a Lambda expression? The term “Lambda” comes from mathematics, where it's called lambda calculus. In programming, a Lambda expression (or function) is just an anonymous function, i.e., a function with no name.

What is meant by lambda expression?

A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.


1 Answers

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.

like image 177
Stilgar Avatar answered Oct 22 '22 11:10

Stilgar