Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
switch Statement | Control Structures
C# Basics

switch Statementswitch Statement

The switch statement functions similarly to the conditional statements however it is useful in specific situations.

The syntax for the switch statement is the following:

The resultant of the expression is compared against the cases x, y, z, and so forth. If it matches a case, it executes the code block of that case. If no case is matched then the default code block is executed if it is provided. The expression is most commonly a variable. We write the break keyword after each case's code block to indicate the end of that case.

Following is an example:

cs

main.cs

You can try changing the value of the variable grade to see the change in the output. The value of grade is compared against each case and the relevant output is displayed.

The same code can be written using if-else statements as well; however in this case the switch statement is more efficient and neater. Whenever we have to compare the result of an expression against many possible values, we use the switch statement.

¿Todo estuvo claro?

Sección 3. Capítulo 11
course content

Contenido del Curso

C# Basics

switch Statementswitch Statement

The switch statement functions similarly to the conditional statements however it is useful in specific situations.

The syntax for the switch statement is the following:

The resultant of the expression is compared against the cases x, y, z, and so forth. If it matches a case, it executes the code block of that case. If no case is matched then the default code block is executed if it is provided. The expression is most commonly a variable. We write the break keyword after each case's code block to indicate the end of that case.

Following is an example:

cs

main.cs

You can try changing the value of the variable grade to see the change in the output. The value of grade is compared against each case and the relevant output is displayed.

The same code can be written using if-else statements as well; however in this case the switch statement is more efficient and neater. Whenever we have to compare the result of an expression against many possible values, we use the switch statement.

¿Todo estuvo claro?

Sección 3. Capítulo 11
some-alt