ใน C # คุณสามารถใช้คำสั่งสวิตช์หนึ่งคำสั่งภายในคำสั่งสวิตช์อื่น เป็นไปได้ที่จะมีสวิตช์เป็นส่วนหนึ่งของลำดับคำสั่งของสวิตช์ภายนอก แม้ว่าค่าคงที่ตัวพิมพ์ของสวิตช์ด้านในและด้านนอกจะประกอบด้วยค่าทั่วไป ก็จะไม่เกิดข้อขัดแย้ง
ต่อไปนี้เป็นรูปแบบไวยากรณ์
switch(ch1) {
case 'A':
Console.WriteLine("This A is part of outer switch" );
switch(ch2) {
case 'A':
Console.WriteLine("This A is part of inner switch" );
break;
case 'B': /* inner B case code */
}
break;
case 'B': /* outer B case code */
} ต่อไปนี้คือตัวอย่างคำสั่งสวิตช์ที่ซ้อนกันใน C#
switch (a) {
case 100:
Console.WriteLine("This is part of outer switch ");
switch (b) {
case 200:
Console.WriteLine("This is part of inner switch ");
break;
}
break;
} มาดูตัวอย่างฉบับสมบูรณ์กันเถอะ
ตัวอย่าง
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int a = 100;
int b = 200;
switch (a) {
case 100:
Console.WriteLine("This is part of outer switch ");
switch (b) {
case 200:
Console.WriteLine("This is part of inner switch ");
break;
}
break;
}
Console.WriteLine("Exact value of a is : {0}", a);
Console.WriteLine("Exact value of b is : {0}", b);
Console.ReadLine();
}
}
} ผลลัพธ์
This is part of outer switch This is part of inner switch Exact value of a is : 100 Exact value of b is : 200