Search code examples
c#lambda

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.


Solution

  • 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?