Creating a function "choose(a, b [, c...])" to choose a random item that has been passed

I’m currently porting over a game from Construct 2, which has a “Choose” function, as described here:

choose(a, b [, c…])
Choose one of
the given parameters at random. E.g.
choose(1, 3, 9, 20) randomly picks one
of the four numbers and returns that.
This also works with strings, e.g.
choose(“Hello”, “Hi”) returns either
Hello or Hi. Any number of parameters
can be used as long as there are at
least two.

What would be the simplest way to implement something like this in C#?

You can create a generic function like this :

public T Choose<T>(T a, T b, params T[] p)
{
	int random = Random.Range(0, p.Length + 2);
	if (random == 0) return a;
	if (random == 1) return b;
	return p[random - 2];
}

To use it, you can call :

int selectedValue = Choose<int>(1, 3, 9, 20);
string selectedString = Choose<string>("Hello", "Hi");

If you don’t like generic types, you can use this non generic version :

public object Choose(object a, object b, params object[] p)
{
	int random = Random.Range(0, p.Length + 2);
	if (random == 0) return a;
	if (random == 1) return b;
	return p[random - 2];
}

There you have to cast the return type to the value you want :

int selectedValue = (int)Choose(1, 3, 9, 20);

But be carefull with this non generic version because it also allow calls like :

Choose(1, "Hello", false, someStrangeValueType);

Which could be hard to cast in the expected type…

I would just set up an array containing the elements that can be chosen from (whether strings or ints or whatever). Then choose a random number from a range representing the length of the array, then use that value to call up the element. For instance, if your array is (“hello”, “hi”, “greetings”) and the random number is chosen is 1 then element 1 from your array (“hi”) is passed.