Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more efficient way to run enum values through a switch-case statement in C# than this?

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

like image 697
C Patton Avatar asked Dec 17 '22 01:12

C Patton


2 Answers

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;
like image 111
Reed Copsey Avatar answered Dec 24 '22 01:12

Reed Copsey


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.

like image 30
twk Avatar answered Dec 24 '22 00:12

twk