Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call delegate from string in C#?

Is it possible to call a delegate stored in a variable by its variable name (as a string)? I guess I'd have to use reflection mechanism, but I'm not getting anywhere

Example code:

class Demo {
  public delegate int DemoDelegate();

  private static int One() {
    return 1;
  }

  private static void CallDelegate(string name) {
    // somehow get the value of the variable with the name
    // stored in "name" and call the delegate using reflection
  }

  private static void CallDelegate(string name, DemoDelegate d) {
    d();
  }

  static void main(string[] args) {
    DemoDelegate one = Demo.One;
    CallDelegate(one);
    // this works, but I want to avoid writing the name of the variable/delegate twice:
    CallDelegate("one", one);
  }

}

Is this even possible? If so how?

like image 313
knittl Avatar asked Oct 21 '25 14:10

knittl


1 Answers

Variables barely exist. The only way to reliably call-by-string (in this scenario) would be to store the delegates in a dictionary:

Dictionary<string, DemoDelegate> calls = new Dictionary<string, DemoDelegate>
{
    {"one",one}, {"two",two}
}

Now store that dictionary somewhere (in a field, typically), and do something like:

private int CallDelegate(string name) {
    return calls[name].Invoke(); // <==== args there if needed
}
like image 89
Marc Gravell Avatar answered Oct 24 '25 05:10

Marc Gravell