Switch: Multiple values in one case?
You can't specify a range in the case statement, can do as follows.
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
break;
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
MessageBox.Show("You are only " + age + " years old\n That's too young!");
break;
...........etc.
You have to do something like:
case 1:
case 2:
case 3:
//do stuff
break;
In C# 7 it's possible to use a when clause in a case statement.
int age = 12;
switch (age)
{
case int i when i >=1 && i <= 8:
System.Console.WriteLine("You are only " + age + " years old. You must be kidding right. Please fill in your *real* age.");
break;
case int i when i >=9 && i <= 15:
System.Console.WriteLine("You are only " + age + " years old. That's too young!");
break;
case int i when i >=16 && i <= 100:
System.Console.WriteLine("You are " + age + " years old. Perfect.");
break;
default:
System.Console.WriteLine("You an old person.");
break;
}
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