The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.
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
Here's an alternative version as an Extension Method
using LINQ
.
using System;
using System.Linq;
public static class EnumExtensions
{
public static Enum GetRandomEnumValue(this Type t)
{
return Enum.GetValues(t) // get values from Type provided
.OfType<Enum>() // casts to Enum
.OrderBy(e => Guid.NewGuid()) // mess with order of results
.FirstOrDefault(); // take first item in result
}
}
public static class Program
{
public enum SomeEnum
{
One = 1,
Two = 2,
Three = 3,
Four = 4
}
public static void Main()
{
for(int i=0; i < 10; i++)
{
Console.WriteLine(typeof(SomeEnum).GetRandomEnumValue());
}
}
}
Two
One
Four
Four
Four
Three
Two
Four
One
Three
You could just do this:
var rnd = new Random();
return (MyEnum) rnd.Next(Enum.GetNames(typeof(MyEnum)).Length);
No need to store arrays
Call Enum.GetValues
; this returns an array that represents all possible values for your enum. Pick a random item from this array. Cast that item back to the original enum type.
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