Can a C# lambda expression have more than one statement?

后端 未结 8 1212
花落未央
花落未央 2020-11-29 03:37

Can a C# lambda expression include more than one statement?

(Edit: As referenced in several of the answers below, this question originally asked about \"lines\" rath

8条回答
  •  时光取名叫无心
    2020-11-29 04:21

    (I'm assuming you're really talking about multiple statements rather than multiple lines.)

    You can use multiple statements in a lambda expression using braces, but only the syntax which doesn't use braces can be converted into an expression tree:

    // Valid
    Func a = x => x + 1;
    Func b = x => { return x + 1; };        
    Expression> c = x => x + 1;
    
    // Invalid
    Expression> d = x => { return x + 1; };
    

提交回复
热议问题