I need to generate random color names e.g. \"Red\", \"White\" etc. How can I do it? I am able to generate random color like this:
Random randonGen = new Ran
Put the colors into an array and then choose a random index:
class RandomColorSelector
{
static readonly Color[] Colors =
typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static)
.Select(propInfo => propInfo.GetValue(null, null))
.Cast()
.ToArray();
static readonly string[] ColorNames =
typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static)
.Select(propInfo => propInfo.Name)
.ToArray();
private Random rand = new Random();
static void Main(string[] args)
{
var colorSelector = new RandomColorSelector();
var color = colorSelector.GetRandomColor();
// in case you are only after the *name*
var colorName = colorSelector.GetRandomColorName();
}
public Color GetRandomColor()
{
return Colors[rand.Next(0, Colors.Length)];
}
public string GetRandomColorName()
{
return ColorNames[rand.Next(0, Colors.Length)];
}
}
Note that the sample above simply looks up all static properties of the Color
type. You might want to improve this by checking that the actual return type of the property is a Color
.