Switch
Switch statements execute a code block from a list of case
conditions for which the expression
validates as true
. Switch statements are similar to if/else statements.
Syntax
switch (expression)
{
case alpha:
// Code block
break;
case beta:
// Code block
break;
default:
// Code block
break;
}
A switch
statement includes one or more case
conditions. The case
conditions are evaluated in top-to-bottom order. If none of the case
conditions evaluate to true
, the default
condition is executed. If no default
is defined, the switch statement is bypassed.
Common Switch syntax definitions:
switch
: Definition of theswitch
statement.expression
: The logic eachcase
will be evaluated against.case
: A value theexpression
is matched against. If thecase
matches the result of theexpression
, the code block within thecase
will be executed.break
(recommended): Terminates the switch statement. Recommended at the end of eachcase
anddefault
to terminate the switch once the case has been fulfilled. A switch statement tests all cases unless abreak
,throw
, orreturn
statement is used to direct control out of the switch. If nobreak
statement exists in a case, C# will throw a compile time error.default
(optional): The behavior executed if nocase
condition matches theexpression
.
Codebyte Example
The following example creates a string variable named favoriteTurtle
with the value of "Donatello"
. A switch statement is defined that evaluates the value of favoriteTurtle
. If a case matches the value of favoriteTurtle
, a corresponding message is printed to the console. If none of the cases in the switch statement match the value of favoriteTurtle
, a default message is printed to the console.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C#
Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.Beginner Friendly23 hours