C# Case Example
C# Case Example
C# Case Example
You are interested in specifics about the case keyword and the syntax for using cases in switch
statements in the C# programming language. The case keyword provides a way to specify a
constant to be matched in the switch selection statement, and cases can be stacked and combined.
Here we look closely at the case keyword in the C# language and see how it can be applied in a
switch statement to control the flow of the execution engine.
using System;
class Program
{
static string TestCase(string value)
{
const string _special = "constant";
Multiple of ten
Multiple of ten
Multiple of fifty
*
Invalid
Using several case statements together. The program text shows the TestCase method and
internally this method uses several case statements in a switch statement. The first three cases are
stacked on top of each other and this is a valid syntax for matching multiple cases to a single
executable code block. At the end of each case statement block, you must have a break, return or
goto jump statement for the program to compile correctly.
Omitting parentheses in case blocks. The program text also shows how it is possible for you to
omit the surrounding parenthesis in a case block in the switch statement. This option is useful for
very large or deeply nested switches, or switch statements that have many very short blocks.
There is no difference in the compiled program if you omit the parentheses.
Using constant identifier instead of constant directly. The switch statement in the TestCase
method also shows how you can use a constant field or local constant in the case statements. The
C# compiler will internally treat this constant the same way as explicitly specified constants in
other cases.
Default case. The program text also shows the default case statement in the switch statement.
The keyword default actually matches all values that are not matched by the specified case
statements.
Summary
Here we looked at the case keyword in the C# programming language and explored its usage in
a simple example program. The case statement in a switch statement is specified with a constant,
which can be either directly embedded in the statement or the identifier of a constant defined
elsewhere. We saw how you can combine or stack case statements. We also compared the case
keyword to the default statement in a switch construct.
See Keywords.