0

My application is defining the method name to the string at runtime. And I want to call that method from string.

Example

private void ButtonClick(){
    string goVoid;
    goVoid = "testVoid";
    goVoid(); // Calling testVoid
}

testVoid(){
    //code
}
Eren
  • 183
  • 2
  • 13
  • 1
    My gut tells me you're trying to do something the Cthulhu, err... PHP way here... You can do this by using reflection if you **must**, but maybe you should explain the real reason you need to do something like that. Please read about [the XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Lucas Trzesniewski Jan 17 '16 at 23:50
  • Have a look at [reflection](https://msdn.microsoft.com/en-us/library/ms173183.aspx).. but I'd first think about other ways to model your application. – Alex McMillan Jan 17 '16 at 23:51
  • @LucasTrzesniewski, Should i remove my answer and post it as duplicate ? – Orel Eraki Jan 17 '16 at 23:55
  • @OrelEraki well, Enigmativity dupehammered the question (I was on the fence of doing this myself anyway). I'd say leave it, you give proper attribution for the code so its presence is not harmful. – Lucas Trzesniewski Jan 17 '16 at 23:58

1 Answers1

2

You can't call a method by specifying the string name alone in a normal straightforward way, you can only do it by using reflection. Other means will not be dynamic and probably will be a switch flow control that will call the method you need based on a match.

For the following you will need System.Reflection

string methodName = "testVoid";
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(methodName);
theMethod.Invoke(this, null);

Source: https://stackoverflow.com/a/540075/303254

Community
  • 1
  • 1
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
  • The OP may need to use the binding flags `BindingFlags.NonPublic | BindingFlags.Instance` if `testVoid` is `private`. His code is not very clear on this. – Enigmativity Jan 17 '16 at 23:54
  • You're right, didn't wanted to over complicated things, i'm still wondering if to remove my answer and mark it as duplicate. – Orel Eraki Jan 17 '16 at 23:56