Random value from Flags enum

Posted by Chris Porter on Stack Overflow See other posts from Stack Overflow or by Chris Porter
Published on 2010-06-08T21:54:59Z Indexed on 2010/06/08 22:32 UTC
Read the original article Hit count: 440

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about enums