roast_soul
roast_soul

Reputation: 3650

Convert error between Expression and Delegate

We can write below code:

 Func<string, string> func = x => x + x;

We also can write:

 Expression<Func<string, string>> exp = x => x + x;

But when I write :

Expression<Func<string, string>> exp = func;

The compiler throw an error:

Cannot implicitly convert type 'System.Func' to 'System.Linq.Expressions.Expression>'

So I change the code as below:

  Expression<Func<string, string>> exp = (Expression<Func<string, string>>)func;

Same error as before.

So what's the real type of x => x + x; , what's the relation between Expression and Delegate/Lambda Expression?

Upvotes: 4

Views: 399

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500815

So what's the real type of x => x + x;

It doesn't have one. A lambda expression is implicitly convertible into compatible delegate types and expression tree types (with some restrictions) but that decision is made at compile-time, and different code is generated depending on what the target of the conversion is.

You can convert from an expression tree to a delegate at execution time (using LambdaExpression.Compile) but you can't go the other way.

Basically, a lambda expression is a source representation of some logic. The compiler can either generate a code representation of that logic (conversion to delegate) or a data representation of that logic (conversion to expression tree). To be very specific, for expression trees, code is generated that will build the data representation.

Upvotes: 6

Related Questions