In Expression Trees, what is the best technique to invoke an instance method?

c# expression-trees linq

Question

What is the best way to call an instance method within an Expression Tree? My current solution is something like this for an interface method "object GetRowValue(rowIndex)" of the interface IColumn.

public static Expression CreateGetRowValueExpression(
    IColumn column, 
    ParameterExpression rowIndex)
        {
            MethodInfo methodInfo = column.GetType().GetMethod(
                "GetRowValue",
                BindingFlags.Instance | BindingFlags.Public,
                null,
                CallingConventions.Any,
                new[] { typeof(int) },
                null);
            var instance = Expression.Constant(column);
            return Expression.Call(instance, methodInfo, rowIndex);            
        }

Is there a faster way? Is it possible to create the Expression without having to pass the method name as a string (bad for refactoring)?

1
4
12/27/2008 11:22:32 AM

Accepted Answer

You can do it with a helper method:

MethodCallExpression GetCallExpression<T>(Expression<Func<T>> e)
{
    return e.Body as MethodCallExpression;
}

/* ... */
var getRowValExpr = GetCallExpression(x => x.GetRowValue(0));
8
5/7/2013 12:21:51 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow