Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch: Multiple values in one case?

I have the following piece of code, but yet when I enter "12" I still get "You an old person". Isn't 9 - 15 the numbers 9 UNTIL 15? How else do I handle multiple values with one case?

  int age = Convert.ToInt32(txtBoxAge.Text);    switch (age)     {     case 1 - 8:   MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");     break;     case 9 - 15:   MessageBox.Show("You are only " + age + " years old\n That's too young!");     break;     case 16-100:   MessageBox.Show("You are " + age + " years old\n Perfect.");     break;     default:   MessageBox.Show("You an old person.");     break;   } 
like image 747
vlovystack Avatar asked Oct 16 '12 09:10

vlovystack


People also ask

Can switch case have multiple values?

Switch CaseThe switch cases must be unique constant values. It can be bool, char, string, integer, enum, or corresponding nullable type.

How do you use multiple conditions in a switch case?

You can use multiple conditions in the switch case same as using in JavaScript if statement. You can do that but the switch statement will switch on the result of the expression you provide. Given you have a logical and ( && ) in your expression there are two possible outcomes defined on how && works.


1 Answers

1 - 8 = -7

9 - 15 = -6

16 - 100 = -84

You have:

case -7:     ...     break; case -6:     ...     break; case -84:     ...     break; 

Either use:

case 1: case 2:  case 3: 

etc, or (perhaps more readable) use:

if(age >= 1 && age <= 8) {      ... } else if (age >= 9 && age <= 15) {      ... } else if (age >= 16 && age <= 100) {      ... } else {      ... } 

etc

like image 108
Marc Gravell Avatar answered Oct 08 '22 03:10

Marc Gravell