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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With