John K
John K

Reputation: 28917

lambda expression syntax vs LambdaExpression class

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?

Upvotes: 10

Views: 7899

Answers (4)

Tomas Voracek
Tomas Voracek

Reputation: 5914

Read carefully what errror message is saying. LambdaExpression is not a delegate. It is normal class. Read http://msdn.microsoft.com/en-us/library/system.linq.expressions.lambdaexpression.aspx. Because it has Lambda in name doesn't mean it is same as 'true' lambda.

Upvotes: 1

Bivoauc
Bivoauc

Reputation: 853

To quote MSDN The LambdaExpression type represents a lambda expression in the form of an expression tree. The Expression type, which derives from LambdaExpression and captures the type of the lambda expression more explicitly, can also be used to represent a lambda expression. At runtime, an expression tree node that represents a lambda expression is always of type Expression.

The value of the NodeType property of a LambdaExpression is Lambda.

Use the Lambda factory methods to create a LambdaExpression object.

Upvotes: 2

Dan Tao
Dan Tao

Reputation: 128417

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.

Upvotes: 13

Femaref
Femaref

Reputation: 61497

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.

Upvotes: 2

Related Questions