C# Examples

Menu:


C# Switch Examples

Following examples show switch statement. You can debug examples online.

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.

C# Switch
Output
C# Switch
Output
C# Switch
Output

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.

C# Switch
Output
C# Switch
Output
C# Switch
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# Switch
Output
C# Switch
Output
C# Switch
Output

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# Switch
Output
Enum
C# Switch
Output
Enum
C# Switch
Output

Switch with String

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

See also

  • C# Foreach - how foreach and IEnumerable works debuggable online
  • C# Switch - switch statement examples debuggable online
  • C# Using - using statement examples debuggable online

Tips

By Jan Slama, 30-Jan-2016