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:
xxxxxxxxxx
1
Random random = new Random();
2
3
Type type = typeof(MyEnum);
4
Array values = type.GetEnumValues();
5
int index = random.Next(values.Length);
6
7
MyEnum value = (MyEnum)values.GetValue(index);
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:
xxxxxxxxxx
1
using System;
2
3
namespace Test
4
{
5
public enum CustomColor
6
{
7
Green,
8
Blue,
9
Red,
10
Yellow
11
}
12
13
class Program
14
{
15
public static void Main(string[] args)
16
{
17
Random random = new Random();
18
Type type = typeof(CustomColor);
19
20
Array values = type.GetEnumValues();
21
//Array values = Enum.GetValues(type);
22
23
for(int i = 0; i < 10; ++i)
24
{
25
int index = random.Next(values.Length);
26
CustomColor value = (CustomColor)values.GetValue(index);
27
28
Console.WriteLine(value);
29
}
30
}
31
}
32
}
Output:
xxxxxxxxxx
1
Green
2
Green
3
Yellow
4
Yellow
5
Red
6
Blue
7
Green
8
Yellow
9
Blue
10
Green