Reputation: 481
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?
Upvotes: 0
Views: 175
Reputation: 53958
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
}
Upvotes: 2
Reputation: 156978
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.
Upvotes: 6