Does anyone know if it's possible to include a range in a switch statement (and if so, how)?
For example:
switch (x)
{
case 1:
//do something
break;
case 2..8:
//do something else
break;
default:
break;
}
The compiler doesn't seem to like this kind of syntax - neither does it like:
case <= 8:
No, this isn't possible. There are a few ways I've done this in the past:
Fixed coding:
switch (x)
{
case 1:
//do something
break;
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
//do something else
break;
default:
break;
}
In combination with an if {}
statement:
switch (x)
{
case 1:
//do something
break;
default:
if (x <= 8)
{
// do something
}
else
{
// throw exception
}
break;
}
No, but you can write this, so you at least avoid writing the // do something else
part multiple times.
switch (x)
{
case 1:
//do something
break;
case 2: case 3: case 4: case 5: case 6: case 7: case 8:
//do something else
break;
default:
break;
}
Whilst this wasn't possible when I originally asked this question, through the miracle of C# Pattern Matching, it now is (in C# 7):
switch (i)
{
case var test when test <= 2:
Console.WriteLine("Less than 2");
break;
case var test when test > 2 && test < 10:
Console.WriteLine("Between 2 and 10");
break;
case var test when test >= 10:
Console.WriteLine("10 or more");
break;
}
A blog post on the subject
Short answer : no. It would be possible to write all of the cases there but such a range notation is not supported.
I think you have to use if
statement here or switch to a language where there is a better support for case descrimination.
One possibility is to convert your ranges into integers. For example:
//assuming x>=9 or if (x <= 0) return;
switch((x+12)/7)
{ case 1:Console.WriteLine("one");
break;
case 2:Console.WriteLine("2 through 8 inclusive");
break;
case 3:Console.WriteLine("9 through 15 inclusive");
break;
default: Console.WriteLine("16 or more");
break;
}
If you have so few cases, if
would be much preferred.
You could, handle the explicit cases case by case, and if you only have one range, deal with it in the default case.
you can do
case 2:
case 3:
case 4:
...
case 8:
// code here
break
You can use case fall through:
switch (x)
{
case 1:
//do something
break;
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
//do something else
break;
default:
break;
}
But I'd just use if for this.
You cannot use any conditional statements in a switch case.
If you want to execute the same lines of code for different options then you can do one thing:
switch (i)
{
case 0:
case 1:
case 2:
case 3:
//do something here.
break;
default:
//do something here.
break;
}
精彩评论