Languages
[Edit]
EN

C#/.NET - get random element from enum

5 points
Created by:
AnnLen
1777

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
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.