0

I have few methods say

  • Method1()

  • Method2()

    ...

  • Method5()

Now when I execute my form I want to call these methods randomly and print their output.

How can I do this?

Community
  • 1
  • 1
Sandip
  • 481
  • 1
  • 9
  • 26
  • 2
    share some code, what have you tried so far, what kind of methods do you want to call, do you expect a return value etc... – avidenic Sep 19 '14 at 12:49
  • possible duplicate of [How to generate random int number?](http://stackoverflow.com/questions/2706500/how-to-generate-random-int-number) – ElGavilan Sep 19 '14 at 12:49
  • 1
    Have you tried generating a random number and using a switch case based on that? – Scott Solmer Sep 19 '14 at 12:50
  • possible duplicate of [Access random item in list](http://stackoverflow.com/questions/2019417/access-random-item-in-list) – Matías Fidemraizer Sep 19 '14 at 12:50
  • Why -1 for question? this question is totally different from question http://stackoverflow.com/questions/2706500/how-to-generate-random-int-number. – Sandip Sep 19 '14 at 12:51
  • Also I am not managing any list I just have 5 methods which will print some value. – Sandip Sep 19 '14 at 12:53

2 Answers2

6

Create a list of methods, and pick one. Call that one:

List<Action> list = new List<Action>();
list.Add(this.Method1);

// Get random number
Random rnd = new Random();
int i = rnd.Next(0, list.Count);

// Call
list[i]();

Note that this only works if the signature is the same (in this case having no parameters). Else you could do the adding like this:

list.Add(() => this.Method1(1));
list.Add(() => this.Method2(1, 2));

If the method return a value, you should use Func<T> instead of Action, where T is the output type.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2

You could try some thing like this:

Random rnd = new Random();
// I suppose that you have 5 methods. If you have a greater number of methods
// just change the 6.
var number = rnd.Next(1,6);
switch(number)
{
    case 1:
       // call Method1
    case 2:
      // call Method2 
}
Christos
  • 53,228
  • 8
  • 76
  • 108