2

I want to know what I am doing wrong here:

string grade;
switch (percentageMark)
{
    case (90 - 100):
        grade = "A*";
        break;
    case (80 - 89):
        grade = "A";
        break;
    case (70 - 79):
        grade = "B";
        break;
    case (60 - 69):
        grade = "C";
        break;
    case (50 - 59):
        grade = "D";
        break;
    case (40 - 49):
        grade = "E";
        break;
    case (0 - 39):
        grade = "U";
        break;
}

I get errors saying that "The label 'case -9:' already occurs in this switch statement", but only at cases 3, 4, 5 and 6. Could someone tell me why I am getting these errors

Adam Higgins
  • 705
  • 1
  • 10
  • 25
  • 4
    use if statement here – Ehsan Sajjad Sep 16 '15 at 13:30
  • The short answer is you can't. There is no ranges in C# case statements – rmn36 Sep 16 '15 at 13:32
  • 2
    This isn't doing what you think it's doing. That first one for example compiles to `case (-10):` – theB Sep 16 '15 at 13:32
  • @sab669 - I got that from the question. The compiler error quoted: `The label 'case -9:' already occurs in this switch statement` seems to indicate that this isn't just pseudocode. Maybe I'm just reading it too literally? – theB Sep 16 '15 at 13:38
  • @theB Nope, you're right. I was reading on my phone and missed the last sentence detailing his errors, so I thought it was just psuedocode. – sab669 Sep 16 '15 at 13:43

3 Answers3

4

You cannot have range in case.

you have to use multiple case like:

case 90:
case 91:
case 92:
case 93:
case 94:
...
...
case:100:
        grade = "A*";

or alternatively you can have if statements for applying range :

if(percentageMark >= 90 && percentageMark <=100)
   grade = "A*";
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
3

As Ehsan already pointed that you cannot use range inside case. And in your case it looks like it would be better to use if..else instead of switch case.

Like this:

if(percentageMark >= 90 && percentageMark <=100)
   grade = "A*";
else if(percentageMark >= 80)
   grade = "A";
else if(percentageMark >= 70)
   grade = "B";
else if(percentageMark >= 60)
   grade = "C";
else if(percentageMark >= 50)
   grade = "D";
else if(percentageMark >= 40)
   grade = "E";
else
   grade = "U";
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

Sadly, C#'s switches do not support ranges.

You will have to use if's and else if's.

For your code this would be something like this:

if (value >= 90 && value <= 100)
{
    // Your code
}
else if (value >= 80 && value < 90)
{
    // Your code
}
else if (value >= 70 && value < 80)
{
    // Your code
}

etc.

Of course if you want to use a switch and the grade is always a value between 0 and 100 then you could use this switch:

switch(grade)
{
    case grade > 90:
        // A*
        break;
    case grade > 80:
        // B
        break;
}

etc.

anthonytimmers
  • 258
  • 1
  • 8