Alex Rivera | Logout

Replace Switch/Case with Pattern

Asked 2009-12-01T22:05:49.860
13

I have code very similar to this example three times in a code behind. Each time the switch is toggling off of an option that is sent to it. Each time the code inside the case is exactly the same except for a parameter based off of the case. Is using a switch/case and methods the best way to do this? Should I think of using sometype of design pattern to avoid the repeative switch/case structure?

string option = dropDownList.SelectedValue.ToString();
switch (option.ToUpper())
{
    case "ALPHA":
        // do repeative code method here; only change is a parameter
        break;
    case "BRAVO":
        // do repeative code method here; only change is a parameter
        break;
    case "CHARLIE":
        // do repeative code method here; only change is a parameter
        break;
    case "DELTA":
        // do repeative code method here; only change is a parameter
        break;
    default:
        break;
}
Edit
Report

1 Answer

14

You can construct a table to convert string to parameter value.

var lookup = new Dictionary<string, ParaType> ()  
{
    { "ALPHA", a  },
    { "BETA", b },
    ....
};

ParaType para;
if (lookup.TryGetValue(option, out para))   // TryGetValue, on popular request
{       
   // do repeative code method here; with para
}
answered 2009-12-01T22:09:06.343

Your Answer