Switch Statement based on range of values

A

Alex

Hi,

Is it possible to perform a swicth statement based on a range of values ?

eg.

switch(Answer)

case : 0 - 4 : do something;
break;

case : 5 : do something else
break;

Grateful for any help
 
T

Tim Wilson

Although not through the way that you described, you can accomplish ranges
in the following ways.

If you know that the only values are 0 - 5 then you could let the "default"
case handle 0 - 4...

switch (x)
{
case 5:
{
// Do something.
break;
}
default:
{
// Do something.
break;
}
}

If you would like to explicitly state that 0 - 4 is to be handled the same
way...

switch (x)
{
case 0:
case 1:
case 2:
case 3:
case 4:
{
// Do something.
break;
}
case 5:
{
// Do something.
break;
}
}
 
C

Carlos J. Quintero [.NET MVP]

The Select Case statement of VB.NET allows ranges, but the switch statement
of C# does not. You need to specify each value or to use a default clause.

--

Best regards,

Carlos J. Quintero

MZ-Tools: Productivity add-ins for Visual Studio .NET, VB6, VB5 and VBA
You can code, design and document much faster.
Free resources for add-in developers:
http://www.mztools.com
 
J

JSheble

How about using it thusly:

switch(Answer)
{
case 0:
case 1:
case 2:
case 3:
case 4:
// put your "do" code here
break;
case 5:
// do something else here
break;
}
 
M

mdb

Is it possible to perform a swicth statement based on a range of values ?

As long as you aren't hung up on using 'switch' specifically, you could
just use an if statement...

if ((Answer >= 0) && (Answer <= 4)) { ... }
else if (Answer == 5) { ... }
 
?

=?ISO-8859-1?Q?Andr=E9?=

Alex said:
Hi,

Is it possible to perform a swicth statement based on a range of values ?

eg.

switch(Answer)

case : 0 - 4 : do something;
break;

case : 5 : do something else
break;

Grateful for any help
switch(Answer)
case 0:
case 1:
case 2:
case 3:
case 4:
do something;
break;

case 5 : do something else
break;
 
K

kids_pro

How about:
if (theValue is in theValueArray){
....
}else{
....
}

In PHP the function call in_array(theValue,theValueArray)
 
J

Jon Skeet [C# MVP]

kids_pro said:
How about:
if (theValue is in theValueArray){
....
}else{
....
}

In PHP the function call in_array(theValue,theValueArray)

And in .NET you use Array.IndexOf and compare the result with -1.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top