Could someone please point me toward a cleaner method to generate a random enum member. This works but seems ugly.
Thanks!
public T RandomEnum<T>() { string[] items = Enum.GetNames(typeof( T )); Random r = new Random(); string e = items[r.Next(0, items.Length - 1)]; return (T)Enum.Parse(typeof (T), e, true); }
We can use enum in C for flags by keeping the values of integral constants a power of 2.
public T RandomEnum<T>() { T[] values = (T[]) Enum.GetValues(typeof(T)); return values[new Random().Next(0,values.Length)]; }
Thanks to @[Marc Gravell] for ponting out that the max in Random.Next(min,max) is exclusive.
Marxidad's answer is good (note you only need Next(0,values.Length)
, since the upper bound is exclusive) - but watch out for timing. If you do this in a tight loop, you will get lots of repeats. To make it more random, consider keeping the Random object in a field - i.e.
private Random rand = new Random(); public T RandomEnum<T>() { T[] values = (T[]) Enum.GetValues(typeof(T)); return values[rand.Next(0,values.Length)]; }
If it is a static field, you will need to synchronize access.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With