Switch Statements
This lesson discusses switch statements in C# using an example
We'll cover the following...
Switch Case
Typically this is required when based on different values of a particular expression, different actions need to be performed. The basic construct of a switch case looks as follows:
-
In code block above the
expressioncan have multiple values. Essentially:- string
- integer
-
casesection withconstant-expressioncan have the value as- constant
- expression that results in a constant
-
This decides to which case statement control will transfer
-
The
defaultsection is optional and only gets executed when none of theconstant-expressionmatches with theexpression -
The
jump-statementmust be there at the end of each block to step out of the switch case once a particular statement section gets executed.
Note: There are a number of branching statements or jump-statements available in C# such as
break,continue,goto,returnandthrow.
Example
Let’s take a look at an example of switch cases to better understand the concept.
Code Explanation
In the code above:
-
First the value of variable
inputis set equal to 2. -
Then the
switchfunction is called withinputpassed to it as the parameter. -
As the value of
inputis 2,case 2is executed displaying: Your input for case 2 is: 2 in console.
You can change the value of input in the code above to execute various switch cases.
-
If the value of
inputis changed to 1 then switch case 1 will execute. -
If the value of
inputis changed to a number other than 1 or 2 then thedefaultcase will execute.
This marks the end of our discussion on switch statements. In the next lesson, we will discuss ternary operators in C#.