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; }
Switch CaseThe switch cases must be unique constant values. It can be bool, char, string, integer, enum, or corresponding nullable type.
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 - 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With