0

I have 100 method like

    public void function1() {}
    public void function2() {}
    ....
    public void function100() {}

The question is how can i call these function without calling them one by one? or how can i call a function from a string like:

    string S = "TheFunction"+x.Tostring()+"()";
Tranoze
  • 27
  • 1
  • 5

2 Answers2

0

What class are your methods on? You can get an array of the methods in your class like so:

MethodInfo[] methods = typeof(YourClassNameHere).GetMethods();

Then you can loop and invoke:

String baseName = "function";
foreach(var item in methods) {
   //Check name
    if (item.Name.SubString(0, baseName.Length) == baseName) {
       item.Invoke(classInstanceOfYourClass,null);
    }
}

classInstanceOfYourClass is an object instance of the class on which you are doing this. The second parameter of invoke, (I set it to null) is for passing arguments to the method. If you pass null, you are saying that the method has no arguments.

DWright
  • 9,258
  • 4
  • 36
  • 53
0

The answer for your question is Reflection. You can take a look at the code in this answer Reflection: How to Invoke Method with parameters.

Community
  • 1
  • 1
Gergo Bogdan
  • 199
  • 1
  • 5