-2

I have some int var:

int i = 5

and 3 methods:

public Method1(){}
public Method2(){}
public Method3(){}

How I can call one of this method using his name + variable i? Something like this:

Method4()
{
   Method+i();
}
Rednar
  • 3
  • 1

2 Answers2

0

You could do what you asked for with reflection, but that's really ugly.

What you could do is have them all in a list or array and then access them by index:

var methods = new Action[]{ null, Method1, Method2, Method3 }; 

methods[1](); // this would call Method1, since Method1 is in position 1 of your array.
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • And this would probably I guess can be written in a `for-loop`. Instead of doing `methods[1]` .Right? – itiDi Sep 28 '21 at 09:14
  • Sure, you could access the array any way you would normally access an array. Constant, variable, in a loop, with a for-each loop (watch the null then, maybe it's better to leave it out and have your index not conform to the actual number). – nvoigt Sep 28 '21 at 09:16
0
        if (i == 3)
                Method3();
Lakkes
  • 25
  • 5