Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch Statement in C# [duplicate]

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:
like image 346
Paul Michaels Avatar asked Mar 31 '10 11:03

Paul Michaels


People also ask

What is a switch statement in C?

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

What is switch statement in C with example?

The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single variable.

What is the statement of switch?

In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.

What is the syntax of switch statement?

The syntax of the switch statement is:statement(s); break; case constant 2: statement(s);


1 Answers

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;
}
like image 67
Andy Shellam Avatar answered Oct 10 '22 03:10

Andy Shellam