Compiler Error for Expression / Func Expressions

The screenshot says this. I have overloads as shown in the screenshot. When using a string as the second parameter, the compiler must figure out that the first argument can only be Func, not an expression. But the compiler gives an error message: "A lamda expression with an operator body cannot be converted to an expression tree."

Why can't the compiler determine the correct overload?

Explicit casting does not help. Which works when I create a local variable of type Func and then use it instead.

Used Structure - FakeItEasy 1.24.0

Wtf?

EDIT

Here is the code that shows the behavior:

public static void Main(string[] args) { //compiler error A.CallTo(() => Main(A<string[]>.That.Matches(strings => { return true; }, "description"))); //compiles Func<string[], bool> predicate = strings => { return true; }; A.CallTo(() => Main(A<string[]>.That.Matches(predicate, "description"))); Console.ReadLine(); } 
+7
c # lambda expression compiler-errors fakeiteasy
source share
1 answer

The problem is not calling Matches . It is in a CallTo call that expects an Expression<Action> .

Apparently, Expression not only cannot be a lambda expression with the operator body, but also cannot contain a lambda expression with the operator body.

(I'm not sure if your "put lambda in local variable" solution will work, or if it just fools the compiler and won't work at runtime.)

In this test, I compiled:

 static void Overloaded(Action a, string param) { } static void Overloaded(Expression<Action> e) { } static void CallToAction(Action a) { } static void CallToExprAc(Expression<Action> a) { } static void Main(string[] args) { // Works CallToAction(() => Overloaded(() => { int i = 5; }, "hi")); // Doesn't work - using the Expression overload CallToAction(() => Overloaded(() => { int i = 5; })); // Doesn't work - wrapped in an outer Expression CallToExprAc(() => Overloaded(() => { int i = 5; }, "hi")); } 

Does your "placed in the lambda kernel in local" work, as implemented by FakeItEasy. I suspect that it will work here, but something similar, for example, LINQ-to-SQL will not - it will simply fail at runtime, and not at compile time.

I am not sure if this is a compiler error, specification error or desired behavior. In section 6.5 of the C # specification, we have

Some lambda expressions cannot be converted to expression tree types. Although the conversion exists, it does not run at compile time. This is the case if the lambda expression is:

• Has a block body

• Contains simple or complex assignment operators

• Contains a dynamically linked expression

• is async

which does not say "contains a lambda expression that cannot be converted to an expression tree type."

+6
source share

All Articles