[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1116
  • Last Modified:

negative values in case statements

Hello experts

Can a negative value be passed to a switch/case statement in C#, eg:

int Val;
switch(Val)
case -1:
      //val=-1
      break;
case 1:
      //val=1
      break;
default:
      //something else
      break;

From what I have been trying, it looks like it cannot, then what is the alternative since I need to pass -1

Thanks,
0
4Learning
Asked:
4Learning
3 Solutions
 
BurniePCommented:
You can convert it as string :
 

int Val;
switch(Val.ToString())
case "-1":
      //val=-1
      break;
case "1":
      //val=1
      break;
default:
      //something else
      break;

Open in new window

0
 
JamesApertaCommented:
yes a negative value can be passed in.  The following will print "minus 1" on my console window

int Val = -1;

switch (Val)
{
    case -1: Console.WriteLine("minus 1"); break;
    case 0: Console.WriteLine("zero"); break;
    default: Console.WriteLine("unhandled"); break;
}
0
 
kris_perCommented:

You need to correct two things in the code:

1. put the case statements inside { }

2. initialize Val to some value; otherwise you will get 'use of unassigned variable' error.

Your fixed code will look as following:
            int Val = -1;
            switch (Val)
            {
                case -1:
                    //val=-1
                    break;
                case 1:
                    //val=1
                    break;
                default:
                    //something else
                    break;
            }

Open in new window

0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
4LearningAuthor Commented:

for some reason, the compiler returns the error, cannot pass through case -1:

And whereever I put this piece of code, the error line number always point to the same.
0
 
4LearningAuthor Commented:
Here is the actual error:

Control cannot fall through from one case label ('case "-1":')  to another
0
 
4LearningAuthor Commented:
I found out the problem. That was the only case statement where I had missed putting a break statement.

Thanks to all the experts for your time!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now