Nested switch statement
switch statement in C# permits checking a variable/esteem with a rundown of qualities (cases) and executing the square connected with that case.
At the point when we use switch statement inside another switch statement (a case statement(s)) for example switch statement inside another switch statement, we can say it is a case of a nested switch statement.
Syntax
//outer switch
switch(variable/expression)
{
case <case_value1>:
statement(s);
//inner switch
switch(variable/expression)
{
case <case_value1>:
statement(s);
break;
case <case_value2>:
statement(s);
break;
default:
statement(s);
break;
}
break;
case <case_value2>:
statement(s);
break;
default:
statement(s);
break;
}
C# code for nested switch statement
// C# program to demonstrate example of nested switch statement
using System;
using System.IO;
using System.Text;
namespace JustTechReview
{
class Test
{
// Main Method
static void Main(string[] args)
{
int number;
//input a number
Console.Write("Enter a number (1-3): ");
number = Convert.ToInt32(Console.ReadLine());
//outer switch statement
switch (number)
{
case 1:
//using another case
//it will input R,G or B and print the color
char color;
Console.Write("Enter color value (R/G/B): ");
color = Console.ReadLine()[0];
//validating it using switch case
//inner switch
switch (color)
{
case 'R':
case 'r':
Console.WriteLine("You've choesn \"Red\" color");
break;
case 'G':
case 'g':
Console.WriteLine("You've choesn \"Green\" color");
break;
case 'B':
case 'b':
Console.WriteLine("You've choesn \"Blue\" color");
break;
default:
Console.WriteLine("Invalid color code");
break;
}
break;
case 2:
Console.WriteLine("Input is 2");
break;
case 3:
Console.WriteLine("Input is 3");
break;
default:
Console.WriteLine("Invalid number");
break;
}
//hit ENTER to exit the program
Console.ReadLine();
}
}
}
Here, we have 3 cases:
(Case 1) Using another switch statement, that will give the shading name dependent on the client input (shading code – model “R/r” for “Red”, “G/g” for “Green”, …)
(Case 2) and Case 3) will print a straightforward message.
Output
First run:
Enter a number (1-3): 1
Enter color value (R/G/B): B
You've choesn "Blue" color
Second run:
Enter a number (1-3): 1
Enter color value (R/G/B): r
You've choesn "Red" color
Third run:
Enter a number (1-3): 1
Enter color value (R/G/B): x
Invalid color code
Fourth run:
Enter a number (1-3): 3
Input is 3