How do I select a random value from an enumeration?
Given an arbitrary enumeration in C#, how do I select a random value?
(I did not find this very basic question on SO. I'll post my answer in a minute as reference for anyone, but please feel free to post your own answer.)
Array values = Enum.GetValues(typeof(Bar));
Random random = new Random();
Bar randomBar = (Bar)values.GetValue(random.Next(values.Length));
Use Enum.GetValues to retrieve an array of all values. Then select a random array item.
static Random _R = new Random ();
static T RandomEnumValue<T> ()
{
var v = Enum.GetValues (typeof (T));
return (T) v.GetValue (_R.Next(v.Length));
}
Test:
for (int i = 0; i < 10; i++) {
var value = RandomEnumValue<System.DayOfWeek> ();
Console.WriteLine (value.ToString ());
}
->
Tuesday
Saturday
Wednesday
Monday
Friday
Saturday
Saturday
Saturday
Friday
Wednesday