Jacob Carpenter’s Weblog

October 6, 2008

C# compiler eccentricity of the day: throwing lambda

Filed under: csharp — Jacob @ 4:21 pm

Here at work (gratuitous link; oh yeah, and we’re hiring), we have a Verify helper class. Verify lets you succinctly validate (or verify, if you will) various method invariants. For instance, non-nullness:


The problem with these helper methods is that when an invariant is violated, an exception is thrown far from the actual affected bit of code. Always moving one frame up the call stack to see the real code that’s failing quickly gets annoying.

I started thinking about how to mitigate this problem, and realized that with Visual Studio’s excellent debugger support for delegates, the call site could include an Action<Exception> that just threw (throw-ed?):

Verify.IsNotNull(name, ex => throw ex);

Except that doesn’t compile.

Wrap the lambda body in curly braces (don’t forget the extra semi-colon) and everything works as expected (including the debugger breaking within the lambda!):

Verify.IsNotNull(name, ex => { throw ex; });

But unfortunately that adds so much syntax that the “solution” is more annoying than the problem I was initially trying to solve.

Has anyone run into anything like this before? Does it make any sense why that statement wouldn’t be valid as a lambda expression?

Create a free website or blog at WordPress.com.