How to use switch case instead of if statements?

ken76

Member
Joined
Nov 15, 2018
Messages
23
Programming Experience
5-10
Is it possible to use switch case instead of if statements with the code below this text?

C#:
if number > 20
{
    ............
}
if number > 30
{
    ............
}
if number > 50
{
    ............
}
if number > 70
{
   ............
}
 
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.
 
If you're using C# 9 or later then the case statements support relational operators:
C#:
switch (number)
{
    case > 70:
        // ...
    case > 50:
        // ...
}
You can read for yourself here.
 
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.

Only if else were in use ?
 
Only if else were in use ?

(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
Given that the OP was asking about using a 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.

It's probably worth noting that that would be possible with a 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.
 
Here is the code for what you are looking for.

C#:
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;
}

Thanks
 
Yikes! Why switch (true)? See post #3 for the better approach.

Also why the hanging curly brace on line 1? That's Java style progamming. C# style is to have the brace on the line below.
 
Last edited:
Back
Top Bottom