2

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?

0

5 Answers 5

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

        ....

        break;
    case "B":

        ....

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

}
Sign up to request clarification or add additional context in comments.

Comments

10

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;

}

Comments

2
    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.

Comments

1

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);

Comments

0

What about handling A and B separately and the switch being the decision on State which is the biggest variable. Something like;

char firstCharacter = ScoreOption.ToUpper().CharAt(0);

if(firstCharacter.Equals("A")) {
  ...
}else if(firstCharacter.Equals("B")) {
  ...
}else {
  switch(ScoreOption.Split("_")[1]) {
    case "NY":
      ...
      break;
    case "OH":
      ...
      break;
    default:
      ...
      break;
  }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.