I have a switch statement:
swtich(x)
{
case 1:
...
break;
case 2:
...
break;
}
I want to put the ... code in a function but I want to put the break too... So I want something like that
void func()
{
...;
break;
}
swtich(x)
{
case 1:
func();
case 2:
func();
}
Break gives error (I know why) but what I can do?
You can't. Best you can do is:
swtich(x)
{
case 1:
func();
break;
case 2:
func();
break;
}
See here for a discussion of what break is for:
The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any.
If you put it in a function, how will it know which loop or switch statement it's supposed to apply to?
You can't put the break in another method.
Though if you want case 1 and case 2 to do the same thing, this is legal:
switch (x)
{
case 1:
case 2:
func();
break;
}
As others have said, it's not possible. Look at it this way, what would be the expected behavior be if you were not inside a switch statement when the execution gets to the break; line?
Put the break; statement after the function call. If you want the function to stop execution under a given condition, use the return; statement.
Don't put the break in the function. Plain and simple.
switch(x)
{
case 1:
func();
break;
case 2:
func();
break;
}
Related
How to execute in one case, other cases? I could just copy paste those other cases, or put it to some external function but there is so much code so I dont want to do that.
Example:
switch(foo)
{
case 3:
{
//something
}break;
case 4:
{
//something else
}break;
case 5:
{
//here i want to execute case 3 and case 4
}break;
}
I think that this was previously answered but I can't find how to do it.
C# doesn't have such functionality. You have to create other methods which will do actions for cases 3 and 4 and call them from case 5 branch. I would suggest to create a separate class FooHandler which would handle your value. It's easily extendable and readable.
public class FooHandler
{
private readonly int _foo;
public FooHandler(int foo)
{
this._foo = foo;
}
public void Handle()
{
switch(this._foo)
{
case 3: this.HandleCase3(); break;
case 4: this.HandleCase4(); break;
case 5: this.HandleCase5(); break;
default: throw new ArgumentException("Foo value is invalid");
}
}
private void HandleCase3()
{
// Your code for case 3
}
private void HandleCase4()
{
// Your code for case 4
}
private void HandleCase5()
{
this.HandleCase3();
this.HandleCase4();
}
}
Usage:
var fooHandler = new FooHandler(foo);
fooHandler.Handle();
If you don't want to add methods (you didn't explain why),
you can use Action local variables holding Lambda expressions.
In the example below you can replace the body of the lambdas with whatever code you have for "something" and "something else".
Action also supports passing arguments to the lambda's body if you need them.
Action something = () => { Console.WriteLine("something"); };
Action something_else = () => { Console.WriteLine("something_else"); };
switch (foo)
{
case 3:
something();
break;
case 4:
something_else();
break;
case 5:
something();
something_else();
break;
}
You could also change the switch to two ifs:
if (foo == 3 || foo == 5)
{
//something
}
if (foo == 4 || foo == 5)
{
//something else
}
It would be easier to use if-statements. Here I also used pattern matching to simplify the tests.
if (foo is 3 or 5) {
// something
}
if (foo is 4 or 5) {
// something else
}
So simple and easy to read and understand.
I would argue that the code being intuitive is important; hence, I would suggest defining helper variables that clarify intention.
While not knowing the meaning of 3, 4 and 5, a hypothetical example could be:
var awesomeFoos = new[] { 3, 5 };
var popularFoos = new[] { 4, 5 };
var fooIsAwesome = awesomeFoos.Contains(foo);
var fooIsPopular = popularFoos.Contains(foo);
if (fooIsAwesome)
{
// something (preferably refactored to a separate method)
}
if (fooIsPopular)
{
// something else (preferably refactored to a separate method)
}
, where .Contains() is found in the System.Linq namespace.
An example fiddle is found here.
That being said, though; you seem quite determined that you would prefer to keep your code as-is, to an as large extent as possible. If that is really a high priority, you could consider putting the whole foo-switch logic inside a method and let it call itself twice in the case 5 scenario:
private static void HandleFoo(int foo)
{
switch(foo)
{
case 3:
{
// something
}break;
case 4:
{
// something else
}break;
case 5:
{
HandleFoo(3);
HandleFoo(4);
}break;
}
}
Example fiddle is found here.
(Depending on the content of // something and // something else, this may not be feasible, though.)
I strongly recommend changing the way you want to implement this statement. This method is not suitable for modern applications and is coupled with everything. But if you need to implement as you asked, You can jump between cases by using goto.
For more information Read "jump statements".
int a = 10;
switch (a)
{
case 0:
//Condition1:
//some actions
break;
case 1:
goto case 0;
//or
goto Condition1;
break;
default:
break;
}
Since this is the linear approach you should check conditions in if for each goto in each case(cause you can't Go back to each step)
Another approach is to save all cases in the order you want to execute and run the switch multiple times. I use a while in my example you can use goto if you don't want to use a loop.
Queue<int> cases = new Queue<int>();
//1 is the main switch value
cases.Enqueue(1);
while (cases.Count > 0)
{
int temp = cases.Dequeue();
switch (temp)
{
case 0:
Console.WriteLine("0");
break;
case 1:
Console.WriteLine("1");
cases.Enqueue(3);//run case 3
cases.Enqueue(0);//then run case 0
break;
case 2:
Console.WriteLine("2");
break;
case 3:
Console.WriteLine("3");
break;
default:
break;
}
}
I'm trying to learn programming C# (self taught) and I came to a point where I don't know if switch case can be used like if condition.
Can I make a comparison with switch like this?
switch(var)
{
case var < 10:
//Do something
break;
}
Or this is a case of why if condition is different compared to switch?
Certain comparisons can be done in switch cases via patterns. In your specific scenario, a relational pattern could check if a switch input is < 10.
switch(var)
{
case < 10:
//Do something
break;
}
One significant limitation of patterns is that the values inside them have to be constant. So if you had a variable int x and tried to use it in case < x: it wouldn't work.
https://dotnetcoretutorials.com/2020/08/10/relational-pattern-matching-in-c-9/
Deciding if to use an IF statement or SWITCH statement depends on a number of factors, including the readability of your code. There are times when multiple IF statements provide a more simpler approach than using switch. Other times it would be best to use a switch statement.
The simple answer to your question is yes but it would be best for you to try both in a particular scenario if you want to learn.
For most purposes switch is an alternative way to write an chain of if/else statement
switch(myVar)
{
case 1:
//Do something
break;
case 2:
//Do something
break;
case 3:
//Do something
break;
default:
//Do something else
}
Is equivalent to
if(myVar == 1) {
//Do something
}
else if(myVar == 2) {
//Do something
}
else if(myVar == 3) {
//Do something
}
else {
//Do something
}
In older versions of C# (pre 7.0) case statements were restricted to only testing if values were equal to a constant. However with the introduction of a feature called 'pattern matching' you can do more expressive matches within case statements. Subsequent C# versions have added more and more syntax in this area, but ultimately they don't do anything beyond what can be achieved with an if/else chain. For situations where there are a lot of conditions the switch/case statements are typically easier to read
An example of changes in syntax being allowed C# 9.0
switch(myVar)
{
case == 1:
//Do something
break;
case > 1 and < 3:
//Do something
break;
case == 3:
//Do something
break;
default:
//Do something else
}
Usually I will implement switch case in a method that return particular object. Something like below:
private string testing(string input){
switch(input)
{
case "a":
{
....
return "TestingResult";
}
case "b":
{
....
return "TestingResultB";
}
default:
return null;
}
}
Now I'm wondering if it's possible to write a switch case for value assignment purpose? Something like below:
private string testing(string input){
string TEST="";
switch(input)
{
case "a":
{
....
TEST = "TestingResult";
}
case "b":
{
....
TEST = "TestingResultB";
}
default:
}
return TEST;
}
Of cause it can be achieve by simple If-Else statement, this question is for me to understand more functionality of switch case
Of course, after testing it, I receive error
control cannot fall through from one case label('case: "a"') to another
You need to add break; in each case
private string testing(string input){
string TEST="";
switch(input)
{
case "a":
TEST = "TestingResult";
break;
case "b":
TEST = "TestingResultB";
break;
default:
}
return TEST;
}
As others have mentioned, the braces within each case are unnecessary.
Yes you can. You just have to remember to put a 'jump' statement of some kind (this includes break, goto case, return, or throw), after each case label:
private string testing(string input){
string TEST="";
switch(input)
{
case "a":
TEST = "TestingResult";
break;
case "b":
TEST = "TestingResultB";
break;
}
return TEST;
}
Note, the braces here are unnecessary, and the default isn't required in this construction as it will fall through the switch block if it doesn't match any of the cases.
Further Reading
switch (C# Reference)
What you've written is perfectly legitimate, however there is no point doing the value assignment unless you are going to carry on and do some further operations with it before returning.
To help you with becoming more proficient with switch/case statements:
in your first example you don't need the default, just have a final return at the end of the function
in your second example, you don't need the default at all - you do nothing with it
a switch/case is usually used for multiple options, for example 4 or more. Any less than that and an if/else is equally readable. You should also bear in mind that a switch/case can give you good speed improvements in some cases
I need help with a speech recognition program I'm working on in C#.
This refers the the Switch Statement. If we have an example this this:
//FIRST CASE STATEMENT
case "open chrome":
System.Diagnostics.Process.Start(#"C:\Program Files\Google\Chrome\Application\chrome.exe");
JARVIS.Speak("Loading");
break;
//SECOND CASE STATEMENT
case "Thanks":
JARVIS.Speak("No problem");
break;
How do I make it so that if the first case statement is not said then the second one will not work. But if the first case statement IS said then it will allow for the second one to work.
I'm thinking here I need an IF statement but I'm not sure.
Thanks.
How about
//FIRST CASE STATEMENT
case "open chrome":
System.Diagnostics.Process.Start(#"C:\Program Files\Google\Chrome\Application\chrome.exe");
JARVIS.Speak("Loading");
alocalvariable = true;
break;
Outside switch
if (alocalvariable)
{
JARVIS.Speak("No problem");
alocalvariable = false;
}
You didn't really specify this, but the way this is set up, switch 1 will have to be hit one time for every time you want switch 2 to fire:
bool isValid = false;
switch(whateverYourVariableIsCalled)
{
//FIRST CASE STATEMENT
case "open chrome":
System.Diagnostics.Process.Start(#"C:\Program Files\Google\Chrome\Application\chrome.exe");
JARVIS.Speak("Loading");
isValid = true;
break;
//SECOND CASE STATEMENT
case "Thanks":
if (isValid)
{
JARVIS.Speak("No problem");
}
isValid = false;
break;
}
Switch/Case is like if-else statement, it will only execute one case.
You will need a nested if statement to do this.
To make your code more readable and understandable, you can probably make your cases into a function, and calls the function if satisfy certain condition.
I have two questions with this code:
public int InsertOrUpdateRecord(char _code, string _databaseFileName)
{
switch(_code)
{
case 'N':
// Some code here
case 'U':
// Some code here
}
return 0;
}
It is not accepting char single quote and double quote value.
If I pass _code as string, it gives red underline in case with this error:
Control cannot fall through one case label to another.
The reason for the compilation error is that the case is missing the break
switch (_code)
{
case 'N':
// Some code here
break; // break that closes the case
case 'U':
// Some code here
break; // break that closes the case
}
You need to do a break at the end of the case:
switch (_code)
{
case 'N':
// Some code here
Console.WriteLine("N was passed");
break;
case 'U':
// Some code here
Console.WriteLine("U was passed");
break;
}
Unless you want in either cases to do the same like so:
switch(_char) {
case 'N':
case 'U':
// Common code for cases N and U here...
}
You have to specifically tell the compiler where the case statement halts:
switch(_char) {
case 'N':
// Code here...
break; // The N case ends here.
case 'U':
// Code here with different behaviour than N case...
break; // The U case ends here.
}
The break statement tells the compiler that you're done with that case, and that it has to get out of the switch instruction.
you can either write a break or return statement like the below code.
char _code = 'U';
switch (_code)
{
case 'N':
case 'U':
return;
}
OR,
char _code = 'u';
switch (_code)
{
case 'N':
case 'U':
break;
}
There is no problem with char. See this msdn article about your error.