Creating a constant Expression in C#

c# expression expression-trees lambda

Question

Is there a way to create an expression in C#, that returns a constant value, but also has a parameter?

Using code, it would look like

var expression = x => 5  

So it should match Expression<Func<double, double>> type.

It probably should look like

ParameterExpression param = Expression.Parameter(typeof(double), "parameter");
ConstantExpression constant = Expression.Constant(0.0);
var expression = Expression.SomeMagic(param, constant);
Expression.Lambda<Func<double, double>>(expression);

Accepted Answer

You pass your parameters into Expression.Lambda<>() :

https://msdn.microsoft.com/en-us/library/dd268052(v=vs.110).aspx

So you're looking for something like :

ParameterExpression param = Expression.Parameter(typeof(double), "parameter");
ConstantExpression constant = Expression.Constant(0.0);

var expression = // build the body ...


Expression.Lambda<Func<double, double>>(expression, param);

To return the same parameter, it'd be as simple as :

ParameterExpression param = Expression.Parameter(typeof(double), "parameter");

Expression.Lambda<Func<double, double>>(param, param);

To return the constant value would be :

ParameterExpression param = Expression.Parameter(typeof(double), "parameter");
ConstantExpression constant = Expression.Constant(0.0);

Expression.Lambda<Func<double, double>>(constant, param);


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why