I have an enum
private enum EventColors
{
Aquamarine,
Azure,
BurlyWood,
CadetBlue,
Gainsboro,
Gold,
Gray,
Khaki,
LawnGreen,
LightGreen,
LightSkyBlue,
Linen,
MediumOrchid,
MediumPurple,
MistyRose,
Olive,
OliveDrab,
Orange,
OrangeRed,
Orchid,
PaleTurquoise,
Peru,
Pink,
Plum,
RoyalBlue,
SandyBrown,
SeaGreen,
SteelBlue,
};
I chose the best from System.Drawing.Color and I would like to randomly choose one:
Array values = Enum.GetValues(typeof(EventColors));
Random rnd = new Random();
EventColors randomBar = (EventColors)values.GetValue(rnd.Next(values.Length));
How can I convert random chosen color from my enum to System.Drawing.Color. ? Is this possible without using switch?
You can create Dictionary<EventColors, System.Drawing.Color>
, fill it by this way:
Dictionary<EventColors, System.Drawing.Color> colors = new Dictionary<EventColors, System.Drawing.Color>();
colors.Add(EventColors.Aquamarine, System.Drawing.Color.Aquamarine);
colors.Add(EventColors.Azure, System.Drawing.Color.Azure);
//... other colors
and then:
Array values = Enum.GetValues(typeof(EventColors));
Random rnd = new Random();
EventColors randomBar = (EventColors)values.GetValue(rnd.Next(values.Length));
System.Drawing.Color someColor = colors[randomBar];
OR
You can use reflection:
Array values = Enum.GetValues(typeof(EventColors));
Random rnd = new Random();
EventColors randomBar = (EventColors)values.GetValue(rnd.Next(values.Length));
string name = Enum.GetName(typeof(EventColors), randomBar);
var type = typeof(System.Drawing.Color);
System.Drawing.Color systemDrawingColor = (System.Drawing.Color)type.GetProperty(name).GetValue(null);