C# C# Console

Switch Examples in C#

What is a Switch Statement?

A switch statement tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed.

Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found.

If a case match is found, then the default statement is executed, and the control goes out of the switch block.

 

Switch with Default Section

The following example shows a simple switch statement that has three switch sections. First two sections start with case label followed by constant value. If a value passed to the switch statement matches any case label constant the specified switch section is executed, otherwise the default section is executed. One switch section can contain more than one statements.

Output: One

Switch Without Default Section

If switch doesn’t contain default section and no case label matches the value, no code is executed and control is tranferred outside the switch statement.

Output: ”

Switch with Multiple Case Labels

Before each switch section can be more than one case labels. Such switch section is executed if any of the case labels matches the value.

C# Code:

Output: Jack or Jane

Switch with Enum

Switch can be also used with enum values. Mostly it’s good practice to include also default section and throw an exception for unexpected values.

Enum

C# Code:

Output: Active

Switch with String

Switch can also use string literals to determine which switch section should be executed.

Output: Starting service…

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.