Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate Expressions in Switch Statements in C#

I have to implement the following in a switch statement:

switch(num) {   case 4:     // some code ;     break;   case 3:     // some code ;     break;   case 0:     // some code ;     break;   case < 0:     // some code ;     break; } 

Is it possible to have the switch statement evaluate case < 0? If not, how could I do that?

like image 425
priyanka.sarkar Avatar asked Oct 12 '09 13:10

priyanka.sarkar


People also ask

What can a switch statement evaluate C?

The switch statement in C/C++ works as follows: (1) first it evaluates the expression presented as a condition in the switch statement. (2) stores the result on the stack or using a general-purpose register.

Can we use expression in switch-case in C?

The expression in the switch can be a variable or an expression - but it must be an integer or a character. You can have any number of cases however there should not be any duplicates. Switch statements can also be nested within each other. The optional default case is executed when none of the cases above match.

Can switch statements use expressions?

Java SE 12 introduced switch expressions, which (like all expressions) evaluate to a single value, and can be used in statements.


1 Answers

I know that this topic is pretty old but if someone still looking for the answer now in C# 7 it's possible. Here is an example:

switch (value) {      case var expression when value < 0:          //some code          break;        case var expression when (value >= 0 && value < 5):          //some code          break;       default:          //some code          break; } 
like image 78
Max Avatar answered Sep 28 '22 04:09

Max