C# case Example (Switch Case)Use the case keyword. Case is part of switch statements and will match values.
This keyword is part of switch. We use this keyword to match constant values in switches. Case specifies a constant to be matched in the switch selection statement.Switch
Usage. Cases can be stacked and combined. We can target a case with a goto statement. And "default" is a special kind of case—it is matched when nothing else does.
Cases specify constants that match the selection in a switch statement. The blocks following a specific case statement are only executed when the case constants are matched.
Example: This code demonstrates the case keyword used in different ways. A string switch statement is shown.String Switch
Cases: The first 3 cases are stacked on top of each other. This syntax can match multiple cases to a single executable code block.
Note: At the end of each case statement block, you must have a break, return or goto jump statement for the program to compile.BreakReturnGoto
Default: The default case does not use the "case" keyword. It is the case that is matched when no other cases do.
C# program that uses case statements in switch
static string TestCase(string value)
const string _special = "constant";
// Begin the switch.
// You can use the parentheses in a case body.
return "Multiple of ten";
// You can omit the parentheses and stack the cases.
return "Multiple of fifty";
// You can use a constant identifier in the case.
// You can use the default case.
static void Main()
// Test the method.
Multiple of ten
Multiple of ten
Multiple of fifty
It is possible to omit the surrounding parenthesis in a case block. This option is useful for large or deeply nested switches, or switch statements that have many short blocks.
And: There is no difference in the compiled program if you omit the parentheses.
Also: The switch statement also shows how to use a constant field or local constant in the case statements.
Compiler: The C# compiler will internally treat this constant the same way as explicitly specified constants in other cases.const
Default case. The program shows the default case statement in the switch statement. The keyword "default" matches all values that are not matched by the specified case statements.
The C# language does not allow cases to fall through to the next cases. This means you cannot execute separate code blocks in multiple case statements.
But: You can still stack together multiple cases. This limitation was added to the language to reduce programming mistakes.
A summary. Case is used in switch statements. We also find this keyword in certain goto statements. The case statement is specified with a constant, which may be defined elsewhere.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.