Switch: Multiple values in one case?

vlovystack picture vlovystack · Oct 16, 2012 · Viewed 137.4k times · Source

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

Answer

Marc Gravell picture Marc Gravell · Oct 16, 2012

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