Search code examples
c#enumsenum-flags

Random value from Flags enum


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();
}

Solution

  • var options = Colours.Blue | Colours.Green;
    
    var matching = Enum.GetValues(typeof(Colours))
                       .Cast<Colours>()
                       .Where(c => (options & c) == c)    // or use HasFlag in .NET4
                       .ToArray();
    
    var myEnum = matching[new Random().Next(matching.Length)];