Home > Software design >  Call random method directly instead of using a lot of if-statements, C#
Call random method directly instead of using a lot of if-statements, C#

Time:09-13

Relative newcomer to c# here. Let’s say I have 50 different methods a1(), a2(), … a50() and I want to call a random one. One way to do it is of course to generate a random int, nr, between 1 and 50 and then use a lot of if statements like if(nr == 1){ a1() } and so on. Quite cumbersome - can I do something smarter? Is it for example possible to do something along the lines of creating a string which is initially only “a” and then adding nr as a string and then calling that string as method? Like this:

Public void RandomMethod()
{
    nr = Random.Range(1,51);
    string = ‘a’   nr.tostring();
    string();
}

I know this doesn’t work, but something like this instead of my first idea would save me hundreds of lines of code Any response is appreciated

  •  Tags:  
  • c#
  • Related