How to use C# switch case statements
The C# switch statement is a control flow statement that allows you to choose from multiple statements based on the value of an expression. It provides a way to execute a specific block of code among several options, depending on the value of the expression.
- expression : An integral or string type expression.
- jump-statement : A jump statement that transfers control out of the case body.
The syntax of the switch statement consists of the keyword switch followed by the expression to be evaluated. Within the body of the switch statement, you define different cases using the case keyword, followed by a constant value or an expression. When the switch statement is executed, the expression is evaluated, and control is transferred to the case that matches the value of the expression.
The C# language supports using a switch statement with string variables. The switch statement compares the String objects in its expression with the expressions associated with each case label, using the String.equals method. It's important to note that the switch statement is currently case-sensitive, meaning it distinguishes between uppercase and lowercase characters. However, it would be beneficial to have the ability to specify the StringComparison to use for comparing strings in the switch statement. By using string values in switch cases, the code becomes more readable and eliminates the need for multiple if-else-if chained conditions, resulting in cleaner and more concise code.
If none of the expressions passed to the switch case match any of the case statements, the control will transfer to the default statement. However, if there is no default statement defined, the control will exit the switch statement and continue with the next set of statements outside of the switch block.
int values with Switch..Case
The following C# program shows how to int values work with Switch..Case statement.Full Source C#
The switch case statements in C# allow for the selection of different code blocks based on the value of an expression. If none of the expressions match any of the case statements, the control can be transferred to a default statement or exit the switch block if there is no default statement defined.