Expression Lambda versus Statement Lambda

2019-02-06 04:24发布

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)?

标签: c# lambda
7条回答
时光不老,我们不散
2楼-- · 2019-02-06 04:55

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;
查看更多
登录 后发表回答