LambdaExpression cannot be started with an expression.

c# expression-trees lambda

Question

Similar to John K. one but more particular, and the recommended response doesn't work for me.

It builds successfully:

Expression<Func<object, object>> specificExpression = (object o) => new object();
Expression generalExpression = specificExpression;

This one doesn't, too:

Expression generalExpression = (object o) => new object();

Error during compilation:

Cannot convert lambda expression to type 'System.Linq.Expressions.Expression' because it is not a delegate type

Expression<Func<T1,T2>> comes fromExpression .

I now have a framework with functions that take various expressions, such as typeExpression having to explicitly cast lambdas to the appropriateExpression<Func<T1,T2>> It's annoying when every method call fails.

Any valid explanations as to why this fundamental OOP behavior is flawed in this instance?

1
2
5/23/2017 11:53:16 AM

Accepted Answer

Because the compiler is unable to determine the exact expression type you are attempting to build, the conversion fails. Imagine if you did this.

Expression generalExpression = (object o) => "foo";

What kind of anExpression<Func<object, string>> ? Think aboutExpression<Func<object, object>> or Expression<Func<object, IComparable>> ? The compiler doesn't pretend to understand what you are attempting to achieve, but all of these types would be acceptable final types for the expression tree.

In order to tell the compiler whatever kind of expression you want to create, you must cast via the desired type:

Expression generalExpression = (Expression<Func<object, object>>)
    (object o) => new object();

If you attempted this, you would see a similar compiler error:

Delegate generalDelegate = delegate() { };

Is that aAction , or aThreadStart , or another kind of void-returning delegate that accepts no argument?

8
8/10/2011 8:40:45 PM

Popular Answer

The least complicated version of an expression is evaluated by the C# compiler, as in:

 var x = (object o) => new object();

x ought to be aFunc<object, object> , not anExpression<Func<object, object>> . Since the compiler in this instance has determined that the value is a delegate,Expression may only take the lead (not a delegate)Expression<Func<>> / Expression<Action> Whenever a type may), a compiler fault is raised.

See @Riana's response as well, since the compiler really rewrites the expression form.



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