Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 972
  • 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help 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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

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