Lambda Expression - C# compiler inference

c# expression-trees type-inference


I'm attempting to comprehend the behavior of compiler inference. For instance, in the code snippet below, the run-time type of the generated delegate isFunc<int>

Expression addExpr = Expression.Add(Expression.Constant(2), Expression.Constant(1));
LambdaExpression lambdaExpr1 = Expression.Lambda(addExpr, null);
var compiled = lambdaExpr1.Compile();

The line of code following does not, however, compile. I'm not sure what is confusing here for the compiler to transform it implicitly into.Expression<Func<int>> and give the variable the LambdaExpression type.

LambdaExpression lambdaExp2 = ()=>2+1;

One explanation I can think of is that the lambda expression on the right side may also match the signature of my custom delegate, in which case the compiler would be unable to determine the type of the delegate. But the same explanation also applies to my original code piece. Why can CLR (runtime) determine that it is of typeFunc<int> . And if this is feasible and a close enough inference can be made at runtime, why not the C# compiler as well?

1/1/2018 5:20:34 PM

Accepted Answer

Let me start by restating the query in a more succinct manner.

A lambda expression can be converted to Expression<T> where T is a delegate type compatible with the lambda expression. Expression<T> is derived from LambdaExpression. Why then can we not convert a lambda expression directly to LambdaExpression?

The reason is because the type information passes from the target type for the assignment to the the object being assigned's kind in one of the few instances in C#. When converting a lambda, the compiler must be aware of the delegate type, which is The C# compiler now checks to see whether the lambda is consistent with the specified delegate type rather than inferring the delegate type from the lambda..

Was it possible to create and implement a system such that, in the event that type information was absent and the conversion target wasLambdaExpression , then it would be safe to assume that? Sure. Apart from the fact that nobody needed or wanted that functionality, nothing was holding us back.

However, the response to the query "why doesn't this functionality exist?" remains constant. No justification is necessary for why a feature won't be implemented.. Nobody requested the feature, nor did anybody design, develop, test, or distribute it to consumers. Consequently, no feature.

Instead, non-existent features need a champion to start the process of turning them into actual features. Take it up on the github forum and argue for the feature if it's something you'd want or need. Or, because the compiler is open-sourced, implement it yourself.

1/1/2018 7:12:35 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow