Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random enum in C# 2.0

Tags:

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); } 
like image 887
user10178 Avatar asked Nov 26 '08 05:11

user10178


People also ask

Is enum available in C?

We can use enum in C for flags by keeping the values of integral constants a power of 2.


2 Answers

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.

like image 114
Mark Cidade Avatar answered Sep 21 '22 08:09

Mark Cidade


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.

like image 33
Marc Gravell Avatar answered Sep 22 '22 08:09

Marc Gravell