Switch คือคำสั่งการเลือกที่เลือกส่วนสวิตช์เดียวเพื่อดำเนินการจากรายการตัวเลือกตามรูปแบบที่ตรงกับนิพจน์การจับคู่
คำสั่ง switch มักใช้เป็นทางเลือกแทนโครงสร้าง if-else หากนิพจน์เดียวถูกทดสอบกับสามเงื่อนไขขึ้นไป
คำสั่ง Switch นั้นเร็วกว่า คำสั่ง switch จำนวนเฉลี่ยของการเปรียบเทียบจะเท่ากับหนึ่งโดยไม่คำนึงถึงจำนวนกรณีที่คุณมี ดังนั้นการค้นหากรณีโดยพลการคือ O(1)
การใช้สวิตช์ −
ตัวอย่าง
class Program{
public enum Fruits { Red, Green, Blue }
public static void Main(){
Fruits c = (Fruits)(new Random()).Next(0, 3);
switch (c){
case Fruits.Red:
Console.WriteLine("The Fruits is red");
break;
case Fruits.Green:
Console.WriteLine("The Fruits is green");
break;
case Fruits.Blue:
Console.WriteLine("The Fruits is blue");
break;
default:
Console.WriteLine("The Fruits is unknown.");
break;
}
Console.ReadLine();
}
Using If else
class Program{
public enum Fruits { Red, Green, Blue }
public static void Main(){
Fruits c = (Fruits)(new Random()).Next(0, 3);
if (c == Fruits.Red)
Console.WriteLine("The Fruits is red");
else if (c == Fruits.Green)
Console.WriteLine("The Fruits is green");
else if (c == Fruits.Blue)
Console.WriteLine("The Fruits is blue");
else
Console.WriteLine("The Fruits is unknown.");
Console.ReadLine();
}
}