As part of the funcletizer, I want to replace C # expressions that do not contain parameters with their evaluated constants:
double d = 100.0; Expression<Func<double, double>> ex1 = x => -x; Expression<Func<double>> ex2 = () => -d; Expression result; result = Funcletize(ex1);
I know that I can evaluate an expression by wrapping it in a lambda expression and causing the following:
object result = Expression.Lambda(ex2).Compile().DynamicInvoke();
When an expression contains unrelated parameters, like ex1
above, this of course crashes throwing an InvalidOperationException, as I did not give any parameters. How to check if an expression contains such parameters?
My current solution includes try {} catch (InvoalidOperationException), but this seems a very inelegant and error-prone way:
// this works; by catching InvalidOperationException public static Expression Funcletize(Expression ex) { try { // Compile() will throw InvalidOperationException, // if the expression contains unbound parameters var lambda = Expression.Lambda(ex).Compile(); Object value = lambda.DynamicInvoke(); return Expression.Constant(value, ex.Type); } catch (InvalidOperationException) { return ex; } }
source share