0

I am trying to create a lambda expression of type Expression.Lambda<Action<Controller>> dynamically.

For instance: x => x.Index()

var body = ???
Expression<Action<Controller>> action = Expression.Lambda<Action<Controller>>(body);

I have the controller type (Type) and the controller action (MemberInfo).

2
  • You mean the actual controller is a type derived from Controller? So you actually want something like x => ((ConcreteController)x).Index()? Commented Oct 14, 2012 at 15:15
  • The Controller class is belonging to ASP.NET MVC. All controllers are derived from this class. I also could change my question into: How do I create a lambda expression of type Expression.Lambda<Action<T>>? Commented Oct 14, 2012 at 15:17

1 Answer 1

2

If I understand your question correctly, you would do it using Expression.Call(). Something like:

Expression<Action<T>> CreateCallExpression<T>(MethodInfo method)
{
    var parameter = Expression.Parameter(typeof(T), "x");
    return Expression.Lambda<Action<T>>(
        Expression.Call(parameter, method), parameter);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Do you know how can I add method parameters? I tried Expression.Paramter and Expression.Variable with no success.
That depends, where do you get the value for that parameter? Should it be constant, or from parameter of the expression, or something else?
It should be constant default values (default(T) if possible.
In that case, something like Expression.Call(parameter, method, Expression.Default(typeof(ParameterType))) should work for a method with one parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.