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()+"()"; 
2
  • Can you just pass the number into the function as a parameter? Commented Apr 15, 2015 at 1:17
  • Duplicate shows how to call function with parameters (which covers your case), there probably more specific duplicate - feel free to search for "C# invoke method by name". Commented Apr 15, 2015 at 1:33

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Added further detail.
@Tranoze, did that work for you?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.