how to get parameter names from an expression tree?

c# expression-trees

Question

I have a expression of this type:

Expression<Action<T>> expression

how do I get the parameters names from this expression (optional: and values) ?

example:

o => o.Method("value1", 2, new Object());

names could be str_par1, int_par2, obj_par3

Accepted Answer

Expression<Action<Thing>> exp = o => o.Method(1, 2, 3);
var methodInfo = ((MethodCallExpression)exp.Body).Method;
var names = methodInfo.GetParameters().Select(pi => pi.Name);

Popular Answer

You can get the parameter names from the Parameters property.

For example:

    Expression<Action<string, int>> expr = (a, b) => (a + b).ToString();
var names = expr.Parameters.Select(p => p.Name);  //Names contains "a" and "b"

For the second part, lambda expressions are just uncompiled functions.
Their parameters don't have values until you compile the expression and call the delegate with some values.

If you take the lambda expression i => i.ToString(), where are there any parameter values?




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