That code doesn't make any sense as it is. Any value that would cause any of the latter expressions to be true would also cause the first expression to be true. You'd have to reverse the order for that code to be useful.
else
were in use ?Is it possible to use switch case
Only ifelse
were in use ?
Given that the OP was asking about using a(Ignoring the fact that your predicates should have parentheses)
Not with the code as presented, no; that's a set of N separate, independent if statements. They cannot logically be replaced by a single switch
switch
, I guess I was making the assumption that what they had provided was basically pseudocode and the elses
were implied, but you're probably correct that that is not a safe assumption to make. It's possible that, should number
be greater than 70 in that original example, you might want all four of the actions performed.switch
in C/C++, where you can fall through from one case
with code to another, but C# doesn't allow that. I would assume they did that to prevent unintended consequences if you forgot a break
in a case
.switch (true) {
case (number > 70):
// Code for number > 70
break;
case (number > 50):
// Code for number > 50
break;
case (number > 30):
// Code for number > 30
break;
case (number > 20):
// Code for number > 20
break;
default:
// Code for other cases
break;
}
switch (true)
? See post #3 for the better approach.Not equivalent to the posted code, I'm afraid. In the posted code if number is 31 then two if blocks (if > 20 and if > 30) are run. Your code only runs one caseHere is the code for what you are looking for