Yatrix Yatrix - 1 year ago 64
C# Question

Is there a way to store a function and it's parameters in a variable to call later?

In C#, I want to do something like this.

var fn = // set it to the function and parameters it'll use


In a hypothetical example, say I wanted to return a function with all of the parameters it needed to execute, I just wanted to execute it from somewhere else.

Answer Source

You can create an Action delegate invoking the function with the parameters:

var fn = () => OtherFunction(param1, param2);

If parameters can change before fn being invoked you can make a copy of the parameters assigning them to new variables if are by value or implementing some Clone mechanism if are by reference:

var value1 = param1;  // In case of value types.
var value2 = param2;  // In case of value types.
var fn = () => OtherFunction(value1, value2);

Then invoke the fn action later:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download