wootscootinboogie
wootscootinboogie

Reputation: 8695

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.

Upvotes: 4

Views: 3809

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500695

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.

Upvotes: 8

Andrei
Andrei

Reputation: 56688

Maybe this will make it clearer:

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

These semicolons effectively are for different lines.

Upvotes: 8

twrowsell
twrowsell

Reputation: 467

Using curly braces allow multiple statements in an lambda expression. That's why a semi colon is required to indicate the end of a statement in curly braces.

Upvotes: 2

Related Questions