Languages
[Edit]
EN

C#/.NET - get random element from enum

5 points
Created by:
AnnLen
9180

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:

  1. get enum type object,
  2. get array of available values,
  3. 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

References

  1. Enum.GetValues() Method - Microsoft Docs
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join