Martin
Martin

Reputation: 325

Get arguments from action created from lambda expression

How do I get the arguments 1 and 2 when I only have the Action delegate?

public class Program
{
    public static void Main(string[] args)
    {
        Action act = () => new Program().Test(1, 2);
    }

    public void Test(int arg1, int arg2)
    {
    }
}

Upvotes: 0

Views: 95

Answers (3)

Peter B
Peter B

Reputation: 24280

It can't be done using an Action, but a lambda expression can also be treated as an Expression<Action> and then it becomes possible.

Note that the code below only works for this kind of expression: it uses the knowledge that we have a method call and that we use constants as parameters.

public class Program
{
    public static void Main(string[] args)
    {
        var values = GetParams(() => Test(1, 2));
        foreach (var v in values)
            System.Diagnostics.Debug.Print(v.ToString());
    }

    private object[] GetParams<T>(Expression<Func<T>> expr)
    {
        var body = (MethodCallExpression)expr.Body;
        var args = body.Arguments;
        return args.Select(p => ((ConstantExpression)p).Value).ToArray();
    }

    public int Test(int arg1, int arg2)
    {
        return arg1 + arg2;
    }
}

Upvotes: 0

nvoigt
nvoigt

Reputation: 77364

You cannot. To do that, you would need an Expression<Action> (See Expression in the MSDN) and you cannot convert from an Action to an Expression<Action>, only the other direction.

Further reading

Upvotes: 4

Maksim Simkin
Maksim Simkin

Reputation: 9679

Do you mean something like this:

Action<int,int> act = (a,b) => new Program().Test(a,b);

It could be called than as act(1,2);

Upvotes: 1

Related Questions