Generate random enum in C# 2.0

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);
}

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.


Need Your Help

R Retrieve column name under condition in a matrix

r matrix condition

I have a matrix with 0 or 1 values. When a line has only one "1", I want to get in return the column name in which is the "1" value and in any other cases get "0". For the example below:

Re-Generating Scaffold

ruby-on-rails scaffolding

Is there any way to re-generate views from newly updated model?

Avoid primary key duplicates in Windows Azure

sql azure unique

In Windows Azure table storage, there is no 'type' that allows an auto incrementing ID. I thought I could use 'IsIdentity' but the checkbox is greyed out (this should give me auto incrementing, rig...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.