31

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;
  }
3
  • 2
    This doesn't seem a good case for a switch statement. It would make more sense as a series of if statements.
    – Arran
    Oct 16, 2012 at 9:40
  • 1
    Switch doesn't accept range values for case: Oct 16, 2012 at 9:44
  • "case 1 - 8:" is interpreted as "case -7:"
    – rundekugel
    Jun 17, 2020 at 8:16

10 Answers 10

42

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

1
  • 4
    Even more readable would be methods that calculate each age bracket :) Oct 16, 2012 at 9:42
36

You have to do something like:

case 1:
case 2:
case 3:
//do stuff
break;
2
  • 1
    But in your case i think an If-constuct would be better.
    – Tomtom
    Oct 16, 2012 at 9:41
  • Thanks I did it like this now, but I get a FormatException was unhandled at the age declaration :/
    – vlovystack
    Oct 16, 2012 at 9:43
10

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
  • 2
    Since C#7 was released this has now become the correct answer. Sep 3, 2019 at 8:38
8

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.

3
  • 35
    This is the worst section of code I have seen posted on this website in years. There comes a point where if the solution is bad code you don't even give the author what they actually want because its bad. Oct 16, 2012 at 11:54
  • It was at least useful to show how one could combine a named case with the default case in a single result, instead of having separate or just the default defined. Like case "case_default": default: return x; break;
    – Tiramonium
    Sep 18, 2017 at 16:58
  • It's fine for showing the syntax rules. In practice you'd use it if you had fewer things to test (like 2 or 3), or if you were testing a few non-contiguous numbers, or alpha strings. If more than just a few, I'd probably use something else. An array, or something like an associative array, would be candidates also. Nov 10, 2021 at 16:24
5

You can use ifelse instead.but if you want to know how to use switch in this case.here is an example.

int age = Convert.ToInt32(txtBoxAge.Text);`
int flag;
if(age >= 1 && age <= 8) {
flag = 1;
} else if (age >= 9 && age <= 15) {
 flag = 2;
} else if (age >= 16 && age <= 100) {
 flag = 3;
} else {
 flag = 4;   
}
switch (flag) 

{
 case 1:
  MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
break;
case 2:
  MessageBox.Show("You are only " + age + " years old\n That's too young!");
break;
case 3:
  MessageBox.Show("You are " + age + " years old\n Perfect.");
break;
default:
  MessageBox.Show("You an old person.");
break;
}

hope that helps ! :)

3

In C# 8.0 you can use switch expression syntax which is ideal for your case.

int age = Convert.ToInt32(txtBoxAge.Text);

string message = age switch
{
    >= 1 and <= 8 => $"You are only {age} years old\n You must be kidding right.\nPlease fill in your *real* age.",
    >= 9 and <= 15 => $"You are only {age} years old\n That's too young!",
    >= 16 and <= 100 => $"You are {age} years old\n Perfect.",
    _ => "You an old person.",
};

MessageBox.Show(message);
1

What about this?

switch (true) 
{
    case (age >= 1 && age <= 8):
        MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
    break;
    case (age >= 9 && age <= 15):
        MessageBox.Show("You are only " + age + " years old\n That's too young!");
    break;
    case (age >= 16 && age <= 100):
        MessageBox.Show("You are " + age + " years old\n Perfect.");
    break;
    default:
        MessageBox.Show("You an old person.");
    break;
}

Cheers

0

you can try this.

switch (Valor)
            {
                case (Valor1 & Valor2):

                    break;               
            }
0

There's no way to evaluate multiple values in one 'case'. You could either use an if statement (as others have suggested) or call a method which evaluates the range that the integer belongs to and returns a value which represents that range (such as "minor", "adult", etc.), then evaluate this returned value in the switch statement. Of course, you'd probably still be using an if statement in the custom method.

0

Separate the business rules for age from the actions e.g. (NB just typed, not checked)

enum eAgerange { eChild, eYouth, eAdult, eAncient};
eAgeRange ar;
if(age <= 8) ar = eChild;
else if(age <= 15) ar = eYouth;
else if(age <= 100) ar = eAdult;
else ar = eAncient;
switch(ar)
{
 case eChild: 
     // action
 case eYouth:
     // action
 case eAdult:
     // action
 case eAncient:
     // action
 default: throw new NotImplementedException($"Oops {ar.ToString()} not handled");
}   

`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.