C # lambda syntax with curly braces

delegate int AddDelegate(int a, int b);
AddDelegate ad = (a,b) => a+b;


AddDelegate ad = (a, b) => { return a + b; };

The two above versions of AddDelegate are equivalent. Syntactically, why is it necessary to have a semicolon before and after }in the second AddDelegate? You may get a compiler error ; expectedif one of them is missing.

+4
source share
3 answers

Perhaps this will make it clearer:

AddDelegate ad = (a, b) =>
                 {
                     return a + b;
                 };

These semicolons are effective for different lines.

+8
source

The lambda statement contains a block of statements ... which means that each statement requires an operator terminator. Note that this is similar to the anonymous methods from C # 2:

AddDelegate ad = delegate(int a, int b) { return a + b; };

Think that this looks like the body of a method, therefore:

AddDelegate ad = GeneratedMethod;
...
private int GeneratedMethod(int a, int b) { return a + b; }

, - . return.

lambda ... , .

-. . MSDN. , lambda :)

, lambdas .

+8

-. .

+2

Source: https://habr.com/ru/post/1526770/


All Articles