Why does this lambda expression not compile?
Action a = () => throw new InvalidOperationException();
Conjecture is fine, but I would really appreciate references to the C# language specification or other documentation.
And yes, I know that the following is valid and will compile:
Action a = () => { throw new InvalidOperationException(); };
The context where I would use something like this is described on this blog post.
Hmm. I've got an answer, but it's not great.
I don't believe that there's a "throw" expression. There's a throw statement, but not just an expression. Compare this with "Console.WriteLine()" which is a method invocation expression with a void type.
As a parallel, you can't have a switch statement, or an if statement etc as the body of a lambda on its own. You can only have an expression or a block (section 7.14).
Is that any help?
Here's my take:
throw
is a statement, not an expression.
And the reference:
12.3.3.11 Throw statements
For a statement stmt of the form
throw expr;
the definite assignment state of v at the beginning of expr is the same as the definite assignment state of v at the beginning of stmt.
To explain the essence perhaps one should think about what an expression implies within the C# lambda construct. It is simply syntactic sugar for:
delegate () { return XXX; }
where XXX
is an expression
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