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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With