Getting argument values of MethodCallExpression

c# expression-trees lambda

Question

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 dunno if work for all situations:

    LambdaExpression l = Expression.Lambda(element);

Popular Answer

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();
        }
    }


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