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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | int i = 1; switch (i) { case 1: Console.WriteLine("One"); break; case 2: Console.WriteLine("Two"); Console.WriteLine("Two"); break; default: Console.WriteLine("Other"); break; } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 | int i = 3; switch (i) { case 1: Console.WriteLine("One"); break; case 2: Console.WriteLine("Two"); break; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | int i = 1; switch (i) { case 1: case 2: Console.WriteLine("Jack or Jane"); break; default: Console.WriteLine("Other"); break; } |
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
1 2 3 | public enum State { Active = 1, Inactive = 2 } |
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | State state = State.Active; switch (state) { case State.Active: Console.WriteLine("Active"); break; case State.Inactive: Console.WriteLine("Inactive"); break; default: throw new Exception(String.Format("Unknown state: {0}", state)); } |
Output: Active
Switch with String
Switch can also use string literals to determine which switch section should be executed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | string commandName = "start"; switch (commandName) { case "start": Console.WriteLine("Starting service..."); StartService(); break; case "stop": Console.WriteLine("Stopping service..."); StopService(); break; default: Console.WriteLine(String.Format("Unknown command: {0}", commandName)); break; } |
Output: Starting service…