Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda expression syntax vs LambdaExpression class

Tags:

c#

lambda

This line of code that tries to assign a lambda expression to a LambaExpression typed variable,

LambdaExpression expr = n => n;

it fails with compile error message:

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

So it needs to be a delegate type. Conceptually it seems odd to me because I can build out a LambdaExpression instance using a factory method like so.

Factory Lambda from MSDN

LambdaExpression lambdaExpr = Expression.Lambda(
    Expression.Add(
        paramExpr,
        Expression.Constant(1)
    ),
    new List<ParameterExpression>() { paramExpr }
);

and that's not a delegate type.

It makes we wonder why lambda to LambaExpression cannot work?

like image 717
John K Avatar asked Feb 25 '11 23:02

John K


2 Answers

Well, this does work:

Expression<Func<int, int>> exp = n => n;
LambdaExpression lambda = exp;

Note that Expression<TDelegate> derives from LambdaExpression.

I think the reason you can't just use LambdaExpression as the type is that then the type of n (in your example) could not be inferred.

Consider the fact that you also can't do this, for basically the same reason:

// What is this? An Action? A ThreadStart? What?
Delegate d = () => Console.WriteLine("Hi!");

Whereas you can do this:

Action a = () => Console.WriteLine("Hi!");
Delegate d = a;

It's essentially the same thing.

like image 174
Dan Tao Avatar answered Oct 05 '22 19:10

Dan Tao


Because LambdaExpression is a way to generate lambda expressions at runtime, where as n => n gets converted to a generated class at compile time.

In short: they are two different things to do the same thing, but can't be used together.

like image 27
Femaref Avatar answered Oct 05 '22 17:10

Femaref