Random value from Flags enum
You can call Enum.GetValues
to get an array of the enum's defined values, like this:
var rand = new Random();
Colors[] allValues = (Colors[])Enum.GetValues(typeof(Colors));
Colors value = allValues[rand.Next(allValues.Length)];
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)];
If you don't mind a little casting, and your enum is of underlying int type, the following will work and is fast.
var rand = new Random();
const int mask = (int)(Colours.Blue | Colours.Red | Colours.Green);
return (Colours)(mask & (rand.Next(mask) + 1));
If you only want a single flag to be set, you could do the following:
var rand = new Random();
return (Colours)(0x1 << (rand.Next(3)));