The switch
statement in C# provides a way to handle multiple conditions based on the value of an expression. It's a cleaner alternative to using multiple if-else if
statements when you have several possible values to compare. Let's dive into the syntax and usage of the switch
statement.
1. Basic Syntax:
In this example:
- The
switch
statement evaluates the value ofdayOfWeek
. - Each
case
represents a possible value fordayOfWeek
. - If a match is found, the corresponding block of code executes.
- The
break
statement exits theswitch
block. If omitted, execution will continue to the nextcase
.
2. Switch Statement Features:
Fall-Through: Unlike some other languages, C#
switch
cases fall through by default. In the example, ifdayOfWeek
is "Saturday," it falls through to the "Sunday" case.Multiple Case Values: You can combine cases if you want the same block of code to execute for multiple values.
3. Switch Expression (C# 8.0 and later):
Starting from C# 8.0, you can use switch expressions, which are more concise and allow for more expressive code:
Here, the switch
expression assigns the result directly to a variable (result
) without the need for a separate statement. The _
serves as a wildcard for unmatched cases.
4. Run the Program:
Press F5
or click the "Start Debugging" button to build and run your program. You should see the output based on the value of dayOfWeek
.
5. Experiment:
- Modify the value of
dayOfWeek
and observe how theswitch
statement handles different cases. - Try adding more cases and experimenting with fall-through behavior.
Congratulations! You've learned how to use the switch
statement in C#. In the next tutorial, we'll explore functions and methods.