Fundamentally, is there any difference between a single-line expression lambda and a statement lambda? Take the following code, for example:
private delegate
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:
MyDelegate myDelegate2 = () => {
Console.WriteLine("Test 2");
Console.WriteLine("Test 2");
};
the brackets are mandatory.
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.
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
From the docs (https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions):
Statement lambdas, like anonymous methods, cannot be used to create expression trees.
Same for the OP example, but after C# 6.0, allowing you to use same expression syntax to define normal non-lambda methods within a class. For example:
public static double AreaOfTriangle(double itsbase, double itsheight)
{
return itsbase * itsheight / 2;
}
The above code snippet can be written only if the method can be turned into a single expression. In short, it can be used the expression lambda syntax, but not the statement lambda syntax.
public static double
AreaOfTrianglex(double itsbase, double itsheight) => itsbase * itsheight / 2;
The two are the same - the first is syntactic sugar to the second and both will compile to the same IL.