Switch case giving me an error - c#

I have the following type of code:
String strGroup = Request.QueryString["group"];
switch(strGroup.ToString){
case "Clients":
// do something here
break;
case "Addresses":
// do something here
break;
case "Matters":
// do something here
break;
case "Individuals":
// do something here
break;
case "Organisations":
// do something here
break;
default:
break;
}
But it's giving the following error:
A value of an integral type expected
for
switch(strGroup.ToString){

Change it to this:
switch(strGroup.ToString())
ToString() is a method, not a property. Therefore, you need to have the empty parenthesis.

Since strGroup is already a string, can't you just do the following and avoid a redundant call to .ToString()?
switch(strGroup)

Related

Is it possible to check for null values in switch case statement in C#

I have an object with the property Value. Value is a nullable number. I have some scenarios for the value of value. Usually, for null cases, I use the default case but this time, it is not correct logically. I want to do "X" in case of 100, "Y" in case of no value (the value is null), otherwise, I want to do "Z".
switch (p.Value)
{
case 100:
// DO X
break;
default:
// Do Z
break;
}
I tried writing case is null but it doesn't compile: Invalid expression term 'is' (CS1525). Is it possible or should I use if statements instead?
You can check for null in a switch case, just like any other value, but you can't use is, is is used in casting
switch (p.Value)
{
case 100:
// DO X
case null:
// DO Y
break;
default:
// Do Z
break;
}
Anyway a case where the item is null is only 1 case, therefore you can just check it with an if statement that is warpped around the switch
In your case
if (p.Value == null){
//DO Y;
}else{
switch (p.Value)
{
case 100:
// DO X
break;
default:
// Do Z
break;
}
}
The first option is much cleaner, and you should choose it
Just tryed it
void Main()
{
int? p=null;
switch (p)
{
case null:
break;
case 100:
// DO X
break;
default:
// Do Z
break;
}
}
everything works fine

Is it possible to use the .ToUpper() method in C# on a string value that isn't stored in a variable?

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.

Convert string to type of another variable

If I have a variable "param" that can be either an int, double, or string, how do I assign another string to param in the most efficient way? Currently what I'm doing is something like this:
string s = "5";
switch (param)
{
case param.GetType() == "System.Double":
param = Convert.ToDouble(s);
break;
case param.GetType() == "System.Int32":
param = Convert.ToInt32(s);
break;
case param.GetType() == "System.String":
default:
break;
}
I was hoping to condense it to something like this (pseudo-code):
param = (typeof(param))s;
or
param = s as typeof(param);
you can use
Convert.ChangeType(s,param.GetType())
https://msdn.microsoft.com/en-us/library/dtb69x08(v=vs.110).aspx
or
ConvertTo(s,param.GetType())
https://msdn.microsoft.com/en-us/library/y13battt(v=vs.110).aspx
I'm not sure what your overall goal is with just this piece of code, but you can always just change the type of the variable:
Convert.ChangeType(s, typeof(param));
After which, you can simply assign it.
After thinking about it, you can then just go ahead and use your variable now if it's successful.

Can switch case being used like a void method?

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

Why a SWITCH...CASE not taking 'char'?

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.

Categories

Resources