This question already has answers here:
Multiple cases in switch statement
(24 answers)
Switch case: can I use a range instead of a one number [duplicate]
(16 answers)
Closed 1 year ago.
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;
}
Related
I need to use an extra condition in a switch case in C#. Let's say that we have a couple of cases that required to do Stuff A and B, but case 4 requires Stuff C + Stuff Extra:
public void myFunction(int value)
{
switch(value)
{
case 0:
//Stuff A
break;
case 1:
//Stuff B
break;
case 2:
case 3:
case 4:
//Stuff C
//Am I forced to use an If to a special condition of case 4?
if(value == 4)
{
//Extra stuff for case 4
}
break;
}
}
Is there another way to do it without using an If statement?
I tried a solution with goto and it actually works. Thank you for your answers:
public void myFunction(int value)
{
switch (value)
{
case 0:
//Stuff A
break;
case 1:
//Stuff B
break;
case 2:
case 3:
//Stuff C
break;
case 4: //Requires "Extra stuff" and "Stuff C"
//Extra stuff for case 4
goto case 3;
//another possible cases...
case 5:
//etc
break;
}
}
Please notice that this solution will only work in cases that do NOT require a concrete order in the execution of the statements.
If for example in this case "Extra stuff" must be executed after "Stuff C" the correct way to do it is using an If statement inside case 3.
Here's a bit of an odd one, combining local functions with switch:
I DO NOT recommend writing this code:
void Main()
{
int value = 4;
switch (value)
{
case 0:
//Stuff A
break;
case 1:
//Stuff B
break;
case 2:
case 3:
common234(); void common234()
{
Console.WriteLine("2-4");
}
break;
case 4:
common234();
Console.WriteLine("only 4");
break;
//another possible cases...
case 5:
//etc
break;
}
}
So I have a task from a worksheet at work:
I have to change these Ifs to a switch, but how do i do it? Heres the Ifs:
if (i<0 || i>15) Console.WriteLine ("A");
else if (i%5<2 && i/3>3) Console.WriteLine ("B");
else if (3<i && i<10) Console.WriteLine ("C");
else if (i&2==2) Console.WriteLine ("D");
else Console.WriteLine ("E");
and here is the switch i made, but that one is bad, but i dont know how to make a good one out of it, i hope you can help me with this.
switch (i)
case (i<0):
case (i>15):
Console.WriteLine ("A“)
Break;
Case (i%5<2 && i/3>3) :
Console.WriteLine ("B“)
Break;
case (3<i && i<10) :
Console.WriteLine ("C");
Break;
Case (i&2==2) :
Console.WriteLine ("D");
Break;
Default
Console.WriteLine ("E");
Break;
It doesnt have to run in a programm, it's just a task from a worksheet
I haven't figured out all the rules completely, but I think what you're after is something like this:
The question wants you to realise that you've got a limited number of results, since the first rule is (i<0 || i>15). This can be the default for a switch statement.
Then you need to work out what would happen for all integers 0-15 and write them into the rest of the switch.
So you're after something along the lines of (although this doesn't have your logic - you can figure that out so you understand what's going on):
switch (i)
{
case 0:
case 2:
case 5:
Console.Write("Something")
break;
case 1:
case 7:
Console.Write("Something Else")
break;
default
Console.WriteLine ("A“)
Break;
}
I think it's:
switch (i)
{
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
Console.WriteLine("C");
break;
case 0:
case 1:
case 3:
case 10:
case 11:
case 12:
case 13:
case 14:
Console.WriteLine("E");
break;
case 2:
Console.WriteLine("D");
break;
case 15:
Console.WriteLine("B");
break;
default:
Console.WriteLine("A");
break;
}
Use a separate variable, in which you have to embed the segmentation logic. Here is a sample:
//using enum
public enum MySwitchableVariable {
NotDefined, //optional
LessThanZero,
MoreThanFifteen,
RestOfFiveLessThanTwoAndFactorMoreThanThree, //its too complex to describe
BetweenThreeAndTen,
RestOfTwoIsTwo,
}
Then you have to make a function which takes an integer and spit out a case of this enum:
public MySwitchableVariable calculate(int i) {
var result = MySwitchableVariable.NotDefined;
// your implementation here
return result;
}
finally you may switch that annoying variable like this:
var Variable = calculate(i);
switch(Variable) {
case MySwitchableVariable.LessThanZero:
// you know the rest
is that what you (or your instructor) want?
Simply you can't do this. Using the switch statement entails that the variable in switch can take a number of discrete constant values.
From the documentation:
The switch statement is a control statement that selects a switch
section to execute from a list of candidates.
Furthermore,
Each case label specifies a constant value. The switch statement transfers control to the switch section whose case label matches the
value of the switch expression (caseSwitch in the example). If no case
label contains a matching value, control is transferred to the default
section, if there is one. If there is no default section, no action is
taken and control is transferred outside the switch statement. In the
previous example, the statements in the first switch section are
executed because case 1 matches the value of caseSwitch.
i need to check more than one statement in switch statement to evalute
like
int a=5;
switch(a)
{
case 4,5:
console.write("its from 4 to 5);
break;
}
You want to do:
case 4:
case 5:
//Code goes here.
break;
Remember though C# doesn't allow fall through so you can't do:
case 4:
//Do some stuff here
//fall through to 5
case 5:
//Code goes here.
break;
In c# you stack cases to do this:
case 4:
case 5:
//do something
break;
case 6:
//do something
etc.
This allows you to execute multiple cases for 1 value.
int a=5;
switch(a)
{
case 4:
// Do work here
goto case 5;
case 5:
console.write("its from 4 to 5);
break;
}
or
This is giving a case two labels.
switch(a)
{
case 4:
case 5:
console.write("its from 4 to 5);
break;
}
This is how..
int a=5;
switch(a)
{
case 4:
case 5:
console.write("its from 4 to 5);
break;
}
I just started using C# and I've got a couple of issues.
Is there any way to code the C# equivalent of the VB.NET Select statement like the following?
Select Object.Name.ToString()
Case "Name1"
'Do something
Case "Name2"
'Do something else
Case Else
'Do the default action
End Select
Any help would be greatly appreciated.
Thanks for the input so far now what about if I hook several controls to one event handler as in the following and I want to perform a slightly different action for each control:
Private Sub Button_Click(sender as Object, e as EventArgs) _
Handles button1.Click, Button2.Click
'do a general activity
Select CType(sender, Button).Name
Case button1.Name
'do something
Case button2.Name
'do something else
Case Else
'do the defalut action
End Select
End Sub
Is there any way of doing the above select statement in C# without having to use nested ifs?
I have come to find over time that some VB.NET Select...Case constructs do not apply in C# and the only way around is to write a lot of ifs.
For instance, in VB.NET, you can write:
Dim num as Integer = 5
Select Case num
Case 1 to 10
'do something
Case 11 to 20
'do another thing
Case Else
'do the default
End Select
But there is no switch construct in C# that allows you to do something of this sort. You'll have to code in roundabout like so:
int num = 5;
switch (num)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
//do something
break;
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
//do something else
break;
default:
//do the default
break;
}
Or if you happen to be working with Double or any type which is made up of continuous instead of discrete values, you'll have to use ifs to get the required action.
Reason? C#'s switch requires constants for the various cases. This is different from VB.NET's Select Case which allows writing ranges.
You'd be looking for the switch statement...
switch (Object.Name.ToString())
{
case "Name1":
//Do something
break;
default:
//default
break;
}
Note that the breaks are import, otherwise the program will drop through your cases. You should be able to find this on almost any C# introduction...
Use a switch statement.
switch (object.Name.ToString()) {
case "Name1":
break;
//Do something
case "Name2":
break;
//Do something else
default:
break;
//Do the default action
}
And don't forget that there is a free online conversion tool that allows you to convert VB.net to C# and viceversa.
With C# 7, switch has been significantly enhanced, and it's now possible to apply more conditions within cases, although it's still not as "clean" as the VB version. E.g. you could do something like:
switch (examScore)
{
case int es when es >= 90: grade = "A"; break;
case int es when es >= 80: grade = "B"; break;
case int es when es >= 70: grade = "C"; break;
case int es when es >= 60; grade = "D"; break;
default: grade = "F"; break;
}
Taken from / References:
C# Switches vs. VB Case Statements
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch
It appears I need to use a break in each case block in my switch statement using C#.
I can see the reason for this in other languages where you can fall through to the next case statement.
Is it possible for case blocks to fall through to other case blocks?
Thanks very much, really appreciated!
Yes, you can fall through to the next case block in two ways. You can use empty cases, which don't need a break, or you can use goto to jump to the next (or any) case:
switch (n) {
case 1:
case 2:
case 3:
Console.WriteLine("1, 2 or 3");
goto case 4;
case 4:
Console.WriteLine(4);
break;
}
The enforcement of "break" is there to stop bugs. If you need to force a fall-thru then use "goto case " (replace the with appropriate value)
the following example shows what you can do:
switch(n)
{
case 1:
case 2:
//do something for 1+2
//...
goto case 3;
case 3:
//do something for 3, and also extra for 1+2
//...
break;
default:
//do something for all other values
//...
break;
}
See http://msdn.microsoft.com/en-us/library/06tc147t%28VS.80%29.aspx
C# doesn't support implicit fall through construct, but the break (or goto) nonetheless has to be there (msdn). The only thing you can do is stack cases in the following manner:
switch(something) {
case 1:
case 2:
//do something
break;
case 3:
//do something else
}
but that break (or another jump statement like goto) just needs to be there.
In my C# (.NET 1.1, CF) code, both of these are allowed:
switch (_printerChoice)
{
case BeltPrintersEnum.ZebraQL220:
return new ZebraQL220Printer();
break;
case BeltPrintersEnum.ONeal:
return new ONealPrinter();
break;
default:
return new ZebraQL220Printer();
break;
}
switch (_printerChoice)
{
case BeltPrintersEnum.ZebraQL220:
return new ZebraQL220Printer();
case BeltPrintersEnum.ONeal:
return new ONealPrinter();
default:
return new ZebraQL220Printer();
}
...but with the breaks in, they are grayed out, so considered moot. So, at least in my case, they are allowed but not required.