C# Nested Switch

Like If-Else statement, Switch statement also can be nested in the code of any cases in the outer switch.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;

namespace TestNestedSwitch
{
    class Program
    {
        static void Main(string[] args)
        {
            string title = "student";
            int grade = 2;

            switch( title ){
                case "teacher":
                    Console.WriteLine("You are a teacher.");
                    break;
                case "student":
                    Console.WriteLine("You are a student.");
                    switch( grade ){
                        case 1:
                            Console.WriteLine("You are a freshman.");
                            break;
                        case 2:
                            Console.WriteLine("You are a sophomore.");
                            break;
                        case 3:
                            Console.WriteLine("You are a junior.");
                            break;
                        case 4:
                            Console.WriteLine("You are a senior.");
                            break;
                        default:
                            Console.WriteLine("Unknown");
                            break;
                    }
                    break;
                default:
                    Console.WriteLine("I don't know who you are.");
                    break;
            }
            Console.Read();
        }
    }
}

Output

You are a student.
You are a sophomore.
  • Line 12: Start outer Switch statement and evaluate title's value. title is a string variable.
  • Line 13, 16, 36: These lines are the cases and default clauses of the outer switch statement.
  • Line 13-14: Output "You chose 1." and then jump out switch statement and start to run line 27.
  • Line 18-34: This is the nested inner switch statement. All of them is a switch statement running behind line 17 inside case "student".

What will be happened if the line 25 is changed to "case 2:"?

The answer is that you will get the following error when you compile the program.

The label 'case 2:' already occurs in this switch statement.