Languages
[Edit]
EN

C#/.NET - get random element from enum

5 points
Created by:
aaliyah
471

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

Alternative titles

  1. C#/.NET - get random enum value
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

C# / .NET - random

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join