Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
A switch statement, in C#, is a selection statement that allows for the transfer of program control to a statement list with a switch label that corresponds to the value of the switch expression.
A switch statement is a control statement that executes a set of logic based on the result of a comparison between a controlling expression and the labels specified in the switch block. This type of statement helps in allowing the value of a variable or expression to select the code block for execution from a list of candidates that represent the different possibilities that can occur.
The use of a switch statement results in improved performance and readability when compared to that of the if..else..if.. ladder. A switch statement can contain another switch statement, thus forming a nested switch, which can yield better performance over other approaches.
A switch statement contains the keyword "switch" followed by a controlling switch expression (within parentheses) and a switch block. The switch block can include zero or many switch sections. Each switch section contains the keyword "‘case" followed by a choice (a constant value ending with ":") and the statement list.
After evaluating the expression of the switch statement, control will be transferred to the statement following the "case" label that matches the value of the expression. If there is no matching constant specified in the "case" labels, control is transferred to the statement following the "default" label (if it exists) or to the end of the switch statement.
The expression specified within the parentheses must be an integral type, enum, string, Boolean or type that can be converted to integral type. Each switch section can include multiple "case" labels. The end of every switch section must be unreachable; as a result, the switch section has to end with a jump statement like "break". The constants used in the different "case" labels within a switch statement cannot be repeated.
For example, a switch statement can be used to compare the numerical input value from the user with a list of menu options displayed in an application and then execute the application based on the user's selection.
In contrast to C++, the execution of a switch section in C# is not allowed to “fall through” (continue) to the next switch section.