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.
Related
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
}
I have a program that reads in parameters from a file. The file is read in one line at a time, and each line is checked to see if it holds a specific value or a blank. If line isn't blank space, the value in the line is passed to a switch statement. Here is a part of the swtich statement in question:
switch(stName)
{
//GENERAL section
case "JOBNAME":
_JobName = stValue;
break;
case "RUN AS-OF DATE":
_RunDate = stValue;
break;
case "USER NOTIFICATION EMAIL ADDRESS":
_UserEmailAddr = stValue;
break;
default:
System.Exception ex = new System.Exception("Unexpected parameter");
ex.Data.Add("Config File", oCommandArgs.ConfigFile);
ex.Data.Add("Parm Line", stIniLine);
ex.Data.Add("Delimiter", cDelimiter);
ex.Data.Add("Name", stName);
ex.Data.Add("Value", stValue);
throw ex;
}
The value in stName is converted to upper case prior to going to the switch statement. My question is, is it possible to use the .ToUpper() method on a string value that isn't stored in a variable? Basically, so that the code would resemble something like this:
switch(stName)
{
//GENERAL section
case "Jobname".ToUpper():
_JobName = stValue;
break;
case "Run as-of date".ToUpper():
_RunDate = stValue;
break;
case "User notification e-mail address".ToUpper():
_UserEmailAddr = stValue;
break;
default:
System.Exception ex = new System.Exception("Unexpected parameter");
ex.Data.Add("Config File", oCommandArgs.ConfigFile);
ex.Data.Add("Parm Line", stIniLine);
ex.Data.Add("Delimiter", cDelimiter);
ex.Data.Add("Name", stName);
ex.Data.Add("Value", stValue);
throw ex;
}
This is just to help simplify adding additional parameters.
In a switch statement, the case labels must be compile time constants; the compiler must know the result of the expression at compile time. The result of ToUpper() can not be, in C#, a compile time constant, code has to run in order to know the result, and therefore can't be used as you intend to.
const int one = 1;
const char c = 'c';
case 'c':
case c:
case 1:
case one:
case one + 1:
case default(int):
Are all valid.
int two = 2;
char a = 'a';
case two: //two is a variable
case a: //a is a variable
case 'c'.ToUpper(); //result of ToUpper is not known at compile time
case one.CompareTo(one): //result of CompareTo is not known at compile time
Are not.
Most practical solution? Decide on a casing criteria for your labels, write them all uppercase, or lower case, just be consistent, and then simply format accordingly the variable you are switching on:
switch(stName.ToUpper()) //<<<normalize casing here
{
case "JOBNAME":
_JobName = stValue;
break;
case "RUN AS-OF DATE":
_RunDate = stValue;
break;
...
}
If you have have to deal with localized upper and lower casing then use ToUpperInvariant or ToLowerInvariant. If that is not an option then switch is probably not the right tool for the job and you'll want to solve this with regular if-elseif-else statements.
Yes it is 100% possible and valid to do that on a string. You have access to all string methods doing it that way. However, switch statements require a constant value so you would not be able to do that in a switch. I would take a look at your code again and see why you would need it. Why not just write the value in all caps?
EDIT: Switch statements require a constant value so the way you are intending to use is NOT valid. I have edited my answer to reflect that.
Below is switch case
switch (strID)
{
case ConfigurationManager.AppSettings["Key1"].ToString():
Label1.Visible = true;
break;
case ConfigurationManager.AppSettings["Key2"].ToString():
Label2.Visible = true;
break;
case ConfigurationManager.AppSettings["Key3"].ToString():
Label3.Visible = true;
break;
default:
Label1.Visible = true;
break;
}
But it gives error "A constant value is expected."
I know that you can't have variables in the switch statement.But is any way ?
You can use only constant value in case statement.
Better you can use if statement e.g.
if(ConfigurationManager.AppSettings["Key1"].ToString() == strID)
{
Label1.Visible = true;
}
else if(ConfigurationManager.AppSettings["Key2"].ToString() == strID)
{
Label2.Visible = true;
}
.
.
.
.
.
.
.
else
{
//default
}
You can have variables in switch's CASE statements. But, that must be a compile time constants i.e. `const' variable.
CASE statements need to be constant; by having them be constant it allows the statement to be much more heavily optimised. Switch will generate the equivalent of a hash table with the case statement values as keys. That approach couldn't be used if the values can change.
Values from ConfigurationManager.AppSettings are decided at run-time. So you can not use it in Switch's CASE statements.
You can use if.. else statements as alternative solution.
See - C# switch statement limitations - why?
Assign the 3 values from Web.Config file to 3 different constants like const string key1 = ConfigurationManager.AppSettings["Key1"].ToString() and use them in the cases inside switch instead of giving ConfigurationManager.Appsettings["Key1"].ToString();
I shall provide a piece of code from one method, where I'm trying to handle commands/values from the web-service.
switch (cmdName)
{
case "getShapefile":
switch (cmdValue)
{
case "buildings":
HandleShapeFile(ref shapfile);
break;
}
break;
}
The idea is the next:
I have several commands (about 7, e.g. get{X-Object})
Also there are for about 10 values for each command, so the count of operations is: 70, and they are different.
How is better to handle values and develop a fine design of such an aim?
I'd probably use methods for each of the 7.
switch (cmdName)
{
case "getShapefile":
HandleShapeFiles( cmdValue );
break;
}
and then have the second case statement in the method.
So the idea is, 7 methods, each with their own case statement of 10 options.
you could flatten the switch so you would have no need for multiple switch blocks.
switch(cmdName + "-" + cmdValue)
{
case "getShapefile-buildings":
HandleShapeFile(ref shapfile);
break;
}
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;
}