Switch statement - variable "case"?

15,053

Solution 1

string s = ScoreOption.ToUpper().Trim();
switch(s)
{
    case "A":

        ....

        break;
    case "B":

        ....

        break;
    default:
        if (s.StartsWith("T_"))
        {
        ....
        }                       
        break;

}

Solution 2

You can't have a variable as a case in a switch statement. You'll have to do something like

case "T_NY":
case "T_OH":
break;

etc.

Now what you could do is

switch (ScoreOption.ToUpper().Trim())
{
   case "A":
    break;
   case "B":
    break;
   default: 
//catch all the T_ items here. provided that you have specifed all other 
//scenarios above the default option.
    break;

}

Solution 3

    switch(ScoreOption.ToUpper().Substring(0, 1)) 
    { 
        case "A": 

            .... 

            break; 
        case "B": 

            .... 

            break; 
        case "T":
            ValidateState(ScoreOption);
            .... 
            break; 

    } 

But, yeah, a series of if statements might be better. That's all the switch is going to generate anyway, since the system can't do any fancy jump table tricks on strings.

Solution 4

You could also create a dictionary with functions containing the code to run when the value matches.

var dict = new Dictionary<string, Action<T,U,V>();
dict.Add("A", (x,y,z) => { 
  ...
});
var func = dict[val];
func(v1,v2,v3);
Share:
15,053
dotnet-practitioner
Author by

dotnet-practitioner

Updated on June 04, 2022

Comments

  • dotnet-practitioner
    dotnet-practitioner almost 2 years

    For ScoreOption, I expect to get the following input "A", "B", and T_(state) for example T_NY

    How can I write a case switch statement for the third option T_(state)?

    switch(ScoreOption.ToUpper().Trim())
    {
        case "A":
            ....
            break;
        case "B":
            ....
            break;
        case T_????
            ....
            break;
    }
    

    I might as well write if-else statement?