JL.
JL.

Reputation: 81262

How to get the arguments from an Action?

I have a method that accepts an Action with a signature like:

public void DoSomething(Action code); 

then I would call this method like:

DoSomething(()=> CallSomething("A","B","C"); 

In the DoSomething method, how can I get the argument values?

Another thing to consider is that CallSomething can potentially have optional parameters, meaning I can't just change the signature of DoSomething to -> Expression<Action>

All I need to do is get the argument values, I'm interested in any method that can work.

I've already tried to create a new method which accepts Expression<Action> then pass the Action through (From DoSomething), but the arguments weren't populated.

Any suggestions welcome.

Upvotes: 0

Views: 436

Answers (1)

Luaan
Luaan

Reputation: 63732

The point is you don't want to.

Your method accepts an Action delegate. It's saying "I only want something to call that has no arguments and returns no value".

If you need to pass arguments to the function, either use a different delegate, or pass them as arguments directly.

Think about this without the lambda. You have an interface that has a single method, Act that takes no arguments and returns no value.

DoSomething(IMyInterface myInterface)
{
  myInterface.Act(); // How do I get the arguments of some method that `Act` calls?
}

Does this make any sense whatsoever? Would you expect to be able to disassemble the whole instance that's passed in myInterface, find its Act method, go through all of the methods that are called from there and intercept their arguments? Delegates are little but a single-method interface with a bit of state carried over.

If you need the arguments, make them part of the public interface. Otherwise, your abstraction has no meaning whatsoever, and you shouldn't be using it. Nobody is forcing you to use lambdas, and nobody is forcing you to pass a single lambda and no arguments, and nobody is forcing you to use Action in particular. They are all simple tools - if they don't fit your task, don't use them.

To answer your question more directly: you get the arguments as any other arguments. The problem is that your action has no arguments.

Upvotes: 3

Related Questions