0

I want to do something like this

int x = 2;
int y = 3;

int performAction(int var1, int var2) {
    return var1 + var2;
}

//accepts function with parameters as parameter
void runLater(performAction(x, y));

The values of x and y could change before performAction is run.

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
Ko Junki
  • 11
  • 3
  • 1
    Hint. Search on these terms: method pointer / delegate / Func<> – Igor Oct 24 '19 at 15:47
  • Delegates are the droids you are looking for. | Technically you could also make a interface, write a concerete class that implements it, make a instance and then hand it it. But you got Delegates, so that is only overly complex. I just mentioned it for completeness. – Christopher Oct 24 '19 at 15:49
  • 1
    `void runLater(Action act);` usage: `runLater(() => performAction(x, y));`. You're passing in an anonymous function that has references to `x` and `y`. – 15ee8f99-57ff-4f92-890c-b56153 Oct 24 '19 at 15:50
  • I would suggest to have a closer look at [this answer](https://stackoverflow.com/a/7766484/5174469) – Mong Zhu Oct 24 '19 at 15:54
  • 1
    @MongZhu That was exactly what I needed. Thank you – Ko Junki Oct 24 '19 at 16:11
  • I'm nominating this to be re-opened because the duplicate link doesn't seem to address variable capture which is a central element of this question. – Ruzihm Oct 24 '19 at 17:48
  • @Ruzihm " variable capture which is a central element of this question." what makes you think so? could you explain? – Mong Zhu Oct 25 '19 at 06:36
  • @MongZhu this part "The values of x and y could change before performAction is run." means that not just any delegate or function passing will work. [user1538301's answer](https://stackoverflow.com/a/58544934/1092820) below should work for you – Ruzihm Oct 25 '19 at 06:37
  • @Ruzihm I think this needs more clarification from OP's side. I would need more information before I would reopen this question – Mong Zhu Oct 25 '19 at 13:43

1 Answers1

0

Signature would be:

void runLater(Func<int, int, int> functionParameter);

You'd call it exactly as shown above in your question;

runLater(performAction);

If you need it to be performed the parameters provided outside of runLater:

// signature would be:
void runLater(Func<int> functionParameter);
// invocation like:
var x = 2;
var y = 3;
runLater(delegate () { return performAction(x, y);});
// or
runLater(() => performAction(x, y));
gabriel.hayes
  • 2,267
  • 12
  • 15