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?