Switch는 일치 표현식과의 패턴 일치를 기반으로 후보 목록에서 실행할 단일 스위치 섹션을 선택하는 선택 문입니다.
switch 문은 단일 표현식이 세 개 이상의 조건에 대해 테스트되는 경우 if-else 구문의 대안으로 자주 사용됩니다.
Switch 문이 더 빠릅니다. switch 문 평균 비교 횟수는 얼마나 많은 다른 사례가 있는지에 관계없이 1이므로 임의의 사례 조회는 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();
}
}