Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Action lambda limitation

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.

like image 650
Jacob Carpenter Avatar asked Oct 31 '08 17:10

Jacob Carpenter


2 Answers

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?

like image 121
Jon Skeet Avatar answered Nov 16 '22 19:11

Jon Skeet


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

like image 15
leppie Avatar answered Nov 16 '22 19:11

leppie