C# Syntax lambdas 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 the } in the second AddDelegate? You can a compiler error ; expected if either one is missing.

Jon Skeet
people
quotationmark

A statement lambda contains a block of statements... which means you need a statement terminator for each statement. Note that this is similar to anonymous methods from C# 2:

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

Think of it as being like a method body, so:

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

Note how the final semi-colon in the original lambda expression or anonymous method is the terminator for the assignment statement. The semi-colon within the block is the terminator for the return statement.

An expression lambda contains only an expression... which means you don't need a statement terminator.

They're just two different forms of lambda expression. See MSDN for more details. If you only have one statement and don't want to include the semi-colon, just use an expression lambda instead :)

Note that statement lambdas cannot currently be converted into expression trees.

people

See more on this question at Stackoverflow