CSharp Switch Statements - How To Control Your Code
November 10, 2023
• 480 views
In this video, we'll be looking at how to use the switch statement in C#. We'll be covering everything from basic usage to more complex scenarios. If you're a beginner or you just want to learn more about the switch statement, this video is for you! By the end of this tutorial, you'll know how to use the switch statement to control your code.
Read and associated article here;
https://www.devleader.ca/2023/11/02/beginners-csharp-switch-statement-tutorial-how-to-properly-use-a-switch-statement/...
View Transcript
if you're newer to programming you've probably found yourself writing these IFL statements that chain together and they get ridiculously long one of the challenges with this is that the code starts to get unreadable now depending on your level of experience you might have heard of this other option that we have available to us and that's called The Switch statement now a switch statement won't necessarily shrink the number of conditions you have in your if else chain however it can be more expressive so in this video we're going to look at the basics of using a switch statement and if you stay right to the end of this video we'll talk about using switch statements with enums and some of the dangers that you're going to want to avoid now instead of my usual format for these videos I'm not going to jump over to visual
studio to show you code instead I'm going to jump over to a Blog article that I've written on my site Dev leader.com I'll leave a link where you can subscribe to that I send out software engineering topics and net examples and often I have exclusive articles and early access to YouTube videos so if you're looking for more learning opportunities I highly recommend you subscribe there it's totally free all right let's dive into Dev leader.com is Define different cases for that number that we want to handle so you can see when we declare case one here that means that when we're handling this switch statement we're going to exercise this code block here when the number is one so this is functionally equivalent to having something like if number equals one then you would have this line of code within that and then similarly when you
have this case two here that would be like saying else if number equals 2 then then go run this code here you can continue this pattern down for case three as well and then we have this special default case at the bottom and again to use comparisons to if statements the default case is like having an else so when we have a number that is not handled by one of these cases above here we're able to fall into this default case and that means that we would go run this line right here where we're saying the number is neither 1 2 nor three if the number was something like four or five so looking at this example we have on the screen if we were to walk through the flow of this code number is set to five so we would check this and that
case is not true because the number is not one same thing here the number is not two the number is not also three and then we would flow into this default case and we would say well the number is neither 1 2 nor three so that's how this code would execute for a switch statement now you might be looking at that switch statement and saying well I can write if statements without some of the curly braces and I can collapse my whole if else if else chain of if statements into something way shorter than that so isn't that more readable isn't that easier to understand and this is just my friendly reminder to you that having less lines of code is not necessarily something that's more readable it's the same thing if you were to make the argument that you could collapse a bunch of
code onto one really long line one really long line is significantly less readable than many shorter narrow lines that are stacked vertically if you don't believe me try it out in some of your own code because you'll find if you have to keep scrolling with your eyes really far to the right using your scroll bar in your IDE to be able to go read the whole line and then go scroll all the way back it's way more work than having more narrow and more stacked lines of code so in this particular case when we're looking at a switch statement having more lines is not necessarily like it's making it less readable and there's some other properties about switch statements that we're going to look at next that give you some other abilities over if statements so let's go back and check that out now so
continuing on with our original example here some things that we want to look at for switch statements are what we're allowed to put for cases and switch statements have this requirement that we need to have constant values for the cases so if you had a complex if statement logic where the comparisons you were doing to number or other things that you were looking at were not dealing with constants then this switch statement syntax would not necessarily work for you the values that you have After Case must be constant and that has to do with how the compiler translates the switch statement into iil or Intermediate Language one more thing to touch on briefly before we continue on to the next example is the word break that we see here and we can see it for every case including the default case the word break is
required in a switch statement to be able to break out of the condition that we're looking at so for example in this switch statement if the number was one and the case one was matched here break ensures that we're not going to flow go over to the other cases and that might surprise you because if you're not familiar with how this syntax looks you might have thought just by exercising case one and doing this line here that we would automatically be complete but the reality is no we could flow through from case to case without having a break here and we have another keyword that we can use that's not just break and that's return so you are able to return out of a case and leave the entire method by having a return here instead of a break and that applies to all of
the other cases as well as the default case as well so if you needed to exit a method strictly by matching a case you're able to do that with a return and you can return a value out of here as well so two things to keep in mind like I said you must have constant values here and you are able to use breaks or returns here and in fact you will likely want to have breaks and returns throughout this for the most part but what if you don't what if you want to be able to collapse some of these together so for example what if you wanted to do even and odd numbers what if you wanted to say if I have 2 4 6 that I want to be able to have something printed in the console that instead of saying the number is
whatever the number is that it's even or odd well we can go ahead and do that and let's go see how so using another example here we have a switch statement using a string so just to kind of illustrate that we can use strings as well as integers and that's because the cases are constant we can do something like days of the week so here we have Monday Tuesday Wednesday Thursday Friday and what we are trying to do is saying that for any of these it's a weekday and you'll notice that the syntax is slightly different as a result and just like I was saying for even and odd numbers were're able to strip out the break or possible return that you might want to put and have these cases stacked together so that way we can have Monday through Friday all having the same
same sort of Handler for when the case is met at that point we want to be able to break out so that we don't flow to these other cases below so that means if we walk through this example and we have Tuesday being assigned to day of the week when we go into this switch statement we would flow through and say is it Monday nope is it Tuesday yep and then from there we would go into this part of the Handler here exercise this line of code and then break out so you can in fact remove break statements or return statements from the cases and flow between the different cases and this is a perfect example of that to build on top of that if we wanted to look at a weekend and that would mean Saturday or Sunday in this particular case no pun
intended we would be able to flow over these ones because it's not going to match if you had a Saturday as an example but as soon as we got to this case it would and we would go exercise this line similarly for Sunday you would flow through the same way and skip over Saturday but still use the same Handler that Saturday had now before I talk about one of the other patterns that we see very frequently with switch statements and some of the dangers that go along with that I want to walk through a switch expression which is slightly different but the syntax looks very similar this is something newer in C that we're able to use and how we leverage it looks a little bit different so I want to walk through this next example first and then we'll talk about this other usage
of switch statements and some of the dangers that go along with it so on my screen I have what is called a switch expression and if you're looking at it the syntax looks very similar but we're missing some of the keywords and the structure is slightly different so what's going on with the switch expression well the switch expression allows us to get a result out so it's like having something that gets returned and assigned into this variable here on the left side of the equal sign and what we're able to do is say that we want to switch on some variable so the syntax is in sort of this reverse order and we don't have parentheses around value but we have value and then we're going to switch on it and then we have our cases inside here but what's really nice and elegant about
this syntax is that instead of having case written out for every single line we just Define what the case is and then we have this Arrow syntax which is what we use for lambdas anonymous delegates and that kind of thing to be able to define the Handler or in this case the return value that we want to have assigned into this result so if we had an example where we initialized value to the word second so this case right here the way that this would work is that we would go switch on this this condition would not match but this condition would in fact match so this side of the arrow which says the second value would be sort of returned out of this switch expression and then assigned into this string result if we have the word third and it's not going to match
either first or second we would end up going into this default case and the way that we Define that is with this underscore which is a discard in C this Arrow syntax and then the value that we want to have returned so while a normal switch statement allows you to have these cases defined and you can have breaks and returns and then handle things just like you would an IFL statement what's really cool about the switch expression is that it allows you to do something similar with slightly nicer syntax I think it feels a little bit less robust but still very readable and return a value to be assigned into a variable so if you're looking to do an assignment combined with a switch statement it's a really nice and elegant way to be able to do that and now I want to talk about
switch statements with something else and that's going to be enums so let's go check that out on the blog article all right so on my screen I am sharing another example using an enum type with a switch statement and I just have the final uh curly brace cut off here at the bottom I apologize but just wanted to fit this in to make it nice and readable so we have an enum that we've declared up here called user type and it has three values admin moderator and user from there we're just declaring a variable called user type and assigning it to user just for this example so as we step through this particular switch statement what's really nice about switch statements and enums is that we can Define each case based on one of the enum values so if you recall earlier I was saying
that we need to operate with constants the nice thing is that when we're dealing with enums something like usertype doed Min is in fact a constant it's going to map to a numeric value but it's nice and readable for us so when you combine this switch statement with an enum we have the same type of behavior that we saw earlier so I don't need to necessarily walk through how all of this code is handled but I just wanted to show you this nice readability we get when we stack these different cases with the different enum types but what's the danger of using switch statements with enums the examp Le we just checked out looked pretty good it was nice and readable we had a default case everything seemed to check out well in order to understand that we're going to explore enum's next so check
out this video series and it'll start to all make sense
Frequently Asked Questions
What is the main advantage of using a switch statement over a long chain of if-else statements?
The main advantage of using a switch statement is that it can make the code more expressive and readable. While it may not reduce the number of conditions, it organizes them in a way that is easier to follow compared to a long chain of if-else statements.
Can I use non-constant values in the cases of a switch statement?
No, you cannot use non-constant values in the cases of a switch statement. The values after the case keyword must be constant, as this is a requirement for how the compiler translates the switch statement.
What happens if I forget to include a break statement in a switch case?
If you forget to include a break statement in a switch case, the code will continue to execute into the next case, which is known as 'fall-through'. This means that if a case matches, it will not only execute its block but also the blocks of subsequent cases until a break or return statement is encountered.
These FAQs were generated by AI from the video transcript.