EN
C#/.NET - get random element from enum
5
points
In this article we are going to have a look at how to get random element from enum.
Quick solution:
Random random = new Random();
Type type = typeof(MyEnum);
Array values = type.GetEnumValues();
int index = random.Next(values.Length);
MyEnum value = (MyEnum)values.GetValue(index);
Random enum
with typeof
operator example
In this section we get random enum
with typeof
operator.
To get value do following steps:
- get
enum
type object, - get array of available values,
- get random value from the array with Random object.
Check practical example below:
using System;
namespace Test
{
public enum CustomColor
{
Green,
Blue,
Red,
Yellow
}
class Program
{
public static void Main(string[] args)
{
Random random = new Random();
Type type = typeof(CustomColor);
Array values = type.GetEnumValues();
//Array values = Enum.GetValues(type);
for(int i = 0; i < 10; ++i)
{
int index = random.Next(values.Length);
CustomColor value = (CustomColor)values.GetValue(index);
Console.WriteLine(value);
}
}
}
}
Output:
Green
Green
Yellow
Yellow
Red
Blue
Green
Yellow
Blue
Green