views:

185

answers:

5

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

+3  A: 

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?

SLaks
I actually wanted the names of the parameters of the method o => o.Method(par1, par2, par3)
Omu
+2  A: 

How do I get the parameters names from this expression ?

expression.Parameters[0].Name

For your future reference, the documentation is here:

http://msdn.microsoft.com/en-us/library/bb359453.aspx

(optional: and values) ?

This doesn't make any sense to me. Can you explain what you mean by "and values"?

Eric Lippert
by values I meant o => o.Method( "value") // Method(string s) s is name
Omu
I actually wanted the names of the parameters of the method o => o.Method(par1, par2, par3)
Omu
+3  A: 

The parameters for Method? Get the MethodInfo from the expression (at a guess, MethodCallExpression.Method), and then use MethodBase.GetParameters() to get the parameters. (ParameterInfo has various useful properties, including Name).

Jon Skeet
+3  A: 
Expression<Action<Thing>> exp = o => o.Method(1, 2, 3);
var methodInfo = ((MethodCallExpression)exp.Body).Method;
var names = methodInfo.GetParameters().Select(pi => pi.Name);
Mark Seemann
+1  A: 

I actually wanted the names of the parameters of the method o => o.Method(par1, par2, par3)

You have some belief that we're psychic, perhaps.

Anyway, moving on.

I actually wanted the names of the parameters of the method o => o.Method(par1, par2, par3)

The name of the first formal parameter is:

(expression.Body as MethodCallExpression).Method.GetParameters()[0].Name

The expression which is the first argument is

(expression.Body as MethodCallExpression).Arguments[0]

For your future reference, the documentation is here:

http://msdn.microsoft.com/en-us/library/system.linq.expressions.methodcallexpression.arguments.aspx

Eric Lippert