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
You could just switch the label, and then set the colors after the switch statement:
Label label = null;
switch (kvp.Key)
{
case MyEnum.Enum1:
label = Label1;
break;
case MyEnum.Enum2:
label = Label2;
break;
}
label.ForeColor = kvp.Value ? Color.LimeGreen : Color.Red;
Alternatively, you could have a Dictionary<MyEnum, Label>
, and just lookup the label appropriately:
labelDictionary[kvp.Key].ForeColor = kvp.Value ? Color.LimeGreen : Color.Red;
Create a hash table that maps from your enum values to the label. Then you can just look up the label to change, rather than switch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With