Question

I have multiple kinds of Action delegates. Take e.g.:

Action<float> floatAction;
Action<string> stringAction;

I want to store any one of them into one variable, and be able to invoke it later. Is that possible?

SomeSortOfType action = floatAction;
//or
SomeSortOfType action = stringAction;
SomeSortOfType.Invoke();

I could not find a basetype for the Action class, so I'm pretty clueless as to whether this is possible in a way.

Gr.Viller

Was it helpful?

Solution

You can use Delegate class that is the base class for all delegate types.

For example:

Action<float> floatAction = (x) => Console.Write(x * 5);
Action<string> stringAction = Console.WriteLine;

Delegate d1 = floatAction;
d1.DynamicInvoke(4.3f);

d1 = stringAction;
d1.DynamicInvoke("Hello world");

OTHER TIPS

You could use an Action<dynamic> (or Action<object> with casting) if you create new lambdas referencing your Action<>s:

Action<float> floatAction = x => Console.WriteLine(x*3);
Action<string> stringAction = Console.WriteLine;

Action<dynamic> dyn = o => floatAction(o);
dyn(1.5f);
dyn = o => stringAction(o);
dyn("Hello World!");

I'd say Selman22's solution is probably better, but I present this in case it's more useful to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top