Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement - variable "case"?

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?

like image 739
dotnet-practitioner Avatar asked Aug 08 '26 11:08

dotnet-practitioner


2 Answers

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

        ....

        break;
    case "B":

        ....

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

}
like image 94
Andrey Avatar answered Aug 11 '26 01:08

Andrey


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;

}
like image 25
kemiller2002 Avatar answered Aug 11 '26 01:08

kemiller2002



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!