Switch statements
Hello, consider the following code:
Can the switch expression be a expression that evaluates to true or false? like age < 5? or the case pattern can they be an expression that evaluates to true or false like age < 5?
21 Replies
Firstly, a switch expression is something different from what you're using here (although you could actually use a switch expression here!), what you're using is a switch statement
ahh these 2 are 2 different things
my bad sorry, thought switch expression and switch statements were the same but on microsoft learn they mentioned switch statement and not expression, my bad
A switch expression would be something like this
oh ok
is that still use nowadays or swtich statement are prefered?
Different uses
They're two different things, both can be used just fine
Your specific case right here is kinda perfect for switch expressions though
ahh I see
switch statement can evaluate things like "age >5" etc/
Switch statements are useful when you want to execute different code (eg. writing to the console) in different branches of the switch, while switch expressions are used to return different singular values depending on the branch.
ahhh
yes... although I'm not entirely sure what you mean right here
it is returned to what, to title ?
You can do this, yes
yep
yeah I see, let's say we want a range, like age between 5 and 10
we won't be able to use switch statements in this case?
yes you would
Specifically for numbers, you can write things like
case >= 5 and <= 10
oh ok
which will execute the branch if the value is between 5 and 10
the thing is I think in other programming language like Java, I think there we can't do that, that's why I was having a doubt
Yeah, C#'s switch statements are a bit more versatile that in a lot of other languages
yep I see, noted, thanks !!
Since they can match a lot more stuff
If you wanna read more into this, it's called "pattern matching"
It's incredibly powerful and can be used to great extent to achieve some very cool things
yep, will read a bit about that, seems interesting and quick syntax
noted, will try to read about them, then, ty !