Random value from Flags enum
- by Chris Porter
Say I have a function that accepts an enum decorated with the Flags attribute. If the value of the enum is a combination of more than one of the enum elements how can I extract one of those elements at random? I have the following but it seems there must be a better way.
[Flags]
enum Colours
{
Blue = 1,
Red = 2,
Green = 4
}
public static void Main()
{
var options = Colours.Blue | Colours.Red | Colours.Green;
var opts = options.ToString().Split(',');
var rand = new Random();
var selected = opts[rand.Next(opts.Length)].Trim();
var myEnum = Enum.Parse(typeof(Colours), selected);
Console.WriteLine(myEnum);
Console.ReadLine();
}