Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a C# lambda expression consist of a simple if statement, without needing braces?

Tags:

Consider the following lambda expression that is being assigned to an event.

foo.BarEvent += (s, e) => if (e.Value == true) DoSomething(); 

This appears pretty straight-forward and consists of only one line of code. So why am I getting the following 2 errors from the debugger?

Invalid expression term 'if'


Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

To fix this problem, all you have to do is a wrap your if statement in brackets.

foo.BarEvent += (s, e) => { if (e.Value == true) DoSomething(); }; //Errors now disappear! 

I understand what these error messages are stating. What I don't understand is why a single-condition if statement would be a problem for the compiler and why the first lambda assignment is considered broken.

Could someone please explain the problem?

like image 373
RLH Avatar asked Aug 15 '13 13:08

RLH


1 Answers

Without { } you declare an expression body, with { } it's a statement body. See Lambda Expressions (C# Programming Guide):

  • An expression lambda returns the result of the expression

  • A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces [...] The body of a statement lambda can consist of any number of statements.

So, if you want a statement rather than an expression, use braces.

like image 123
CodeCaster Avatar answered Sep 20 '22 15:09

CodeCaster