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)?
The two are the same - the first is syntactic sugar to the second and both will compile to the same IL.
Reflector to the rescue! The disassembled code looks like this:
So no, there is no real difference between the two. Be happy.
No, there is no difference in this example. If the body of the lambda is only one expression, you can drop the brackets. However, once the lambda contains more than one expression, like so:
the brackets are mandatory.
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.
Otherwise they are the same.
If the delegate returns a value,
return
is necessary in statement lambda as follows.Personnaly, i prefer the Lambda Expression. The Expression have a value where the Statement does not.
i think the following links can help you :
http://lambda-the-ultimate.org/node/1044