Random enum

CSharp · Console

/Program.cs

using System;
using System.Linq;
using System.Collections.Generic;

					
public class Program
{
	public static void Main()
	{
		var rand = new Random();
		
		for (int i = 0; i < 20; i++)
		{
			Colors randomColor = rand.GetRandomEnum<Colors>(new List<Colors> {Colors.White, Colors.Black});
			Console.WriteLine(randomColor);
		}		
	}
}

public enum Colors
{
	Red = 0,
	Blue = 1,
	Green = 5,
	Yellow = 3,
	Black = 2,
	White = 6
}

public static class ExtensionMethods {
	public static TEnum GetRandomEnum<TEnum>(this Random rand, IEnumerable<TEnum> excludedValues)
	{
		var type = typeof(TEnum);
		if (!type.IsEnum)
			throw new ArgumentException("Not an enum type");
		
		
		var values = Enum.GetValues(type).Cast<TEnum>();
		
		if (excludedValues != null && excludedValues.Any())
			values = values.Except(excludedValues); 
		
		//create a random index for each possible Enum value 
		//will never be out of bounds because it NextDouble returns a value
		//between 0 (inclusive) and 1 (exclusive)  or [0, 1)
		int randomIndex = (int) (rand.NextDouble() * values.Count());
		return values.ElementAt(randomIndex);
	}	
	
}
;