Felipe Pessoto
Felipe Pessoto

Reputation: 6969

Getting argument values of MethodCallExpression

How can I get the arguments values of a MethodCallExpression?

Today I do this way, but isn´t fast enough:

private static object GetArgumentValue(Expression element)
{
    LambdaExpression l = Expression.Lambda(Expression.Convert(element, element.Type));
    return l.Compile().DynamicInvoke();
}

This method get values from a Expression, but if I know that Expression always come from a MethodCallExpression.Arguments I can optimize it?

I think I can change first line to this, but I don't know if it works for all situations:

LambdaExpression l = Expression.Lambda(element);

Upvotes: 13

Views: 6845

Answers (3)

ttugates
ttugates

Reputation: 6291

This worked for me:

private static object GetArgumentValue(Expression element)
{
    if (element is ConstantExpression)
    {
        return (element as ConstantExpression).Value;
    }

    var l = Expression.Lambda(Expression.Convert(element, element.Type));
    return l.Compile().DynamicInvoke();
}

It is combining the OP's original solution with Sleeper Smith's Answer.

Upvotes: 2

Agrejus
Agrejus

Reputation: 762

I would try this to return the object:

private static object _getValue(MethodCallExpression expression)
{
    var objectMember = Expression.Convert(expression, typeof(object));

    var getterLambda = Expression.Lambda<Func<object>>(objectMember);

    var getter = getterLambda.Compile();

    return getter();
}

It is much faster then calling the following:

LambdaExpression l = Expression.Lambda(Expression.Convert(element, element.Type));
return l.Compile().DynamicInvoke();

Upvotes: 3

Sleeper Smith
Sleeper Smith

Reputation: 3242

Cake

class Program
    {
        static void Main(string[] args)
        {
            Expression<Action<string>> action = a => Console.WriteLine("asdf");
            var mce = action.Body as MethodCallExpression;
            Console.WriteLine((mce.Arguments[0] as ConstantExpression).Value);
            Console.ReadKey();
        }
    }

Upvotes: 4

Related Questions