Yatrix Yatrix - 24 days ago 8
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

fn();


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

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:

fn();
Comments