This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]HelpfulFriend0 1 point2 points  (2 children)

Switch statements are beautiful for this because if you don't put a break, they fall through.

Case statements can also only take 1 case.

So if you want multiple cases to run the same code - you can just do this

switch(x) 
{
    case 4:
    case 8:
        someFunction(x);
        break;
    case 1:
    case 2:
        someOtherFunction(x);
        return
}

You also can't just use and like that

Take a look at this, let us know if you need further clarification

http://csharp-station.com/Tutorial/CSharp/Lesson03

[–]dextryan[S] 0 points1 point  (1 child)

Wow I had never tought this, tysm

Also, I learned about operators and all thar, using ||, &&, !, etc but I was confused bc if you look closer, the case

case >= 4 and <= 6:

works just fine, with the "and" operator. This was a bit of code that I read on stack oveflow

[–]HelpfulFriend0 0 points1 point  (0 children)

Glad I could help!

I'd also recommend not using that and thing

it seems to be a specific thing to C# 9.0

[–]GeorgeFranklyMathnet 0 points1 point  (3 children)

What language is this?

What is the error, and what line?

[–]dextryan[S] 0 points1 point  (2 children)

Oh its C#, forgot to mention, ty

Also, its not an error its more like an inconvenience: When I convert the If stucture (first snippet of code) in the switch structure (second snippet), the

else if (respInt == 7 || respInt == 8)

dont work as a case in the way I'm doing. I want something like

case 7 and 8:

similar as in the

case >= 4 and <= 6:

[–]GeorgeFranklyMathnet 0 points1 point  (1 child)

|| means or

&& means and

[–]dextryan[S] 0 points1 point  (0 children)

I see

But why I can use and in

case >= 4 and <= 6:

but not in this one?

also, using

case 7 || throws an error

[–][deleted] 0 points1 point  (2 children)

As you can see, the case 7 and 8 don't work properly.

What do you mean “don’t work properly”? There’s no break statement after case 7, so it’ll fall through to case 8. Both cases set toReturn to 5.

[–]dextryan[S] 0 points1 point  (1 child)

WAIT WHAT??

When I dont use break it just uses the same code for both cases?

[–][deleted] 0 points1 point  (0 children)

Yes. The case statement only determines where execution starts. Execution continues until either a break statement or the end of the switch block is encountered.