4

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.

Yatrix
  • 13,361
  • 16
  • 48
  • 78

1 Answers1

6

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();
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
  • 5
    Just be careful, if you change the value of `param1` or `pram2` before calling `fn()` [it will use the updated value, not the value at the time the delegate was created](https://blogs.msdn.microsoft.com/matt/2008/03/01/understanding-variable-capturing-in-c/). – Scott Chamberlain Nov 11 '16 at 21:22
  • 1
    @ScottChamberlain: Yes, it's true, it's something to keep in mind. – Arturo Menchaca Nov 11 '16 at 21:24
  • 1
    I've actually done this before and I couldn't for the life of me remember. Chalking this up to after 4:00 on a Friday. Thanks! – Yatrix Nov 11 '16 at 21:36