Question

There are several questions on StackOverlow about statement body expressions. I am just wondering why it is not possible to do this in C#? (Where is the complexity why it was not implemented in the compiler?)

There is great explanation for memberof/infoof from @eric-lippert. Is there a similar explanation for statement body expression conversion?

UPDATE (based on Jon Skeet's answer):

My use-case is the possibility to easily translate the C# code transformations at runtime. I would just like to know where is the large amount of effort? The compiler should already have built some similar expression tree during the compilation -- or is there a hidden complexity like in the case of infoof?

Was it helpful?

Solution

Expression trees were originally created for LINQ, which is about queries. Queries are generally function-based, so single-expression lambdas fit really well, without needing to worry about control flow within the expression tree etc. I suspect that translating expression trees for arbitrary statement lambdas into SQL etc would be a fool's errand.

Expression trees were later enhanced for .NET 4 (largely for the sake of the DLR, I believe) but the C# 4 compiler doesn't actually need to create complicated expression trees from lambda expressions for that - so it's mostly that there just isn't enough benefit for it to be worth it.

To put it another way: what's your use case that would justify the probably-large amount of effort which it would take to include it? Maybe there is such a use case, and maybe in a future version of C# the team will decide it's worth it. But for the moment, being able to convert expression lambdas into expression trees has a clear benefit - but the extra effort of doing the same for statement lambdas doesn't have a corresponding benefit.

EDIT: There's absolutely no reason why the C# compiler would need to have an expression tree representation of code (in terms of System.Linq.Expressions), but it will have an abstract syntax tree.

I suspect what you really want is Roslyn - it's still in CTP, but it's basically a compiler API. The Roslyn AST isn't designed to be used in the same scenarios as expression trees, but if you're interested in compiler transformations, it may well still be what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top