Is there a more efficient way to run enum values through a switch-case statement in C# than this?
- by C Patton
I was wondering if there was a more efficient (efficient as in simpler/cleaner code) way of making a case statement like the one below...
I have a dictionary. Its key type is an Enum and its value type is a bool. If the boolean is true, I want to change the color of a label on a form.
The variable names were changed for the example.
Dictionary<String, CustomType> testDict = new Dictionary<String, CustomType>();
//populate testDict here...
Dictionary<MyEnum, bool> enumInfo = testDict[someString].GetEnumInfo();
//GetEnumInfo is a function that iterates through a Dictionary<String, CustomType>
//and returns a Dictionary<MyEnum, bool>
foreach (KeyValuePair<MyEnum, bool> kvp in enumInfo)
{
switch (kvp.Key)
{
case MyEnum.Enum1:
if (someDictionary[kvp.Key] == true)
{
Label1.ForeColor = Color.LimeGreen;
}
else
{
Label1.ForeColor = Color.Red;
}
break;
case MyEnum.Enum2:
if (someDictionary[kvp.Key] == true)
{
Label2.ForeColor = Color.LimeGreen;
}
else
{
Label2.ForeColor = Color.Red;
}
break;
}
}
So far, MyEnum has 8 different values.. which means I have 8 different case statements..
I know there must be an easier way to do this, I just can't conceptualize it in my head.
If anyone could help, I'd greatly appreciate it. I love C# and I learn new things every day.. I absorb it like a sponge :)
-CP