Welcome back.
In this video, I want to quickly go over when to use switch and when to use if statements in C sharp.
So here are a few scenarios where switch statements are more appropriate and one of them is multiple
distinct options.
So when you have a variable that can take on several distinct values, a switch statement can provide
a more concise and readable way to handle each case, which for example, are months right?
There are only 12 months, and they are super distinct options and very easy to follow along.
Yet it's very nice to have them in order using a switch statement.
Then there are enum types.
We haven't covered enum types yet, but they are very similar.
Basically months are stored as enums, so as the enum type inside of the dotnet framework.
Okay, we're going to cover that later on we're going to look at enum types.
And then you will see how switch statements will even make more sense.
And then it's for improved code readability.
So for cases where you have many possibilities so many possible conditions a switch statement just makes
it look a little nicer.
Switch statements are a little limited in a way in C sharp because they work best with integers, enumerates
and strings, and also with patterns, which is something we'll cover later on, but it does not support
ranges or complex conditions, which is where if statements are super useful.
Also, you get a slightly better performance using switch statements when there are many branches.
However, nowadays it doesn't make that much of a difference because compilers have become really good
at translating them accordingly and compiling it.
So here are a few scenarios where if statements are more appropriate when you have complex conditions.
So for example, conditions which have multiple different things that have to be true, multiple conditions
that have to be true.
So for example the age has to be above 18 and the parent has to be with you, as we had this earlier
example.
Then an if statement is the better choice or the only choice.
Then you have ranged values when you want to say, for example, if the age is between 13 and 18, then
do x, and in that case, if statements are also significantly better, you can do ranges with switch
statements, but they are not really nice, so it doesn't really make sense to do it.
And then when you have dynamic conditions.
So for example if the condition can change during runtime, for example the user enters something or
data is getting loaded from the internet.
That is unpredictable.
So in those cases, an if statement is also the better choice.
Now you saw both variants.
In the end you can use if statements for everything switch statements, not for everything.
So if you're unsure, use an if statement whenever you have very specific numbers that you want to handle
or strings that you want to handle, then a switch statement would be the better way to go.
All right, so that's it for this video.
See you in the next one.