7.1: Switch Case
In this module we'll study switch statements.
File Location
Right click on the solution you made in the first module.
Go to Add > New Project and select Console App (.NET Framework).
Name it
07_conditionals_switch
.Write your code for this module within
Program.cs
of that project.
Description
According to the MSN docs, "a switch statement is a type of conditional that chooses a single switch section to execute from a list of candidates based on a pattern match with the match expression."
It's a bit easier to study switch statements by writing them, so lets do that now.
Switch Case
Below is an example of a switch case that you can add to the Program.cs
file:
Analysis
In the example above, we ask the user their name and then store that name in
inputName
variable. To standardize the input, we use.ToLower()
to convert the user's input to lowercase.Next, we declare a
switch
that takes in theinputName
variable.We write out the various cases. The program looks for fred, then karl, then john, and then has a case for none, if none of these cases are the value. If the value of
inputName
is 'Fred' or 'fred', the switch will execute the Console statement to go golfing.The statement will break out of the switch statemetn and the program will move on to #5.
More Practice
Without looking, try making a switch case that outputs descriptions of your different friends.
It could look like this:
Last updated