switch 제어문은 거의 모든 프로그래밍 언어에 들어있는 기초적인 제어문이다.
우리의 특별한 C#은 switch제어문에서 조금 더 특별한 기능을 제공한다.
switch 제어문의 원형
int num = 1;
switch(num)
{
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
case 3:
case 4:
Console.WriteLine("Three or Four");
break;
default:
Console.WriteLine("Out Of Range");
break;
}
One
이때 switch의 조건식으로는 모든 데이터 타입이 올 수 있다.
모든 객체의 조상인 object도 넣을 수 있다.
object num = 4;
switch (num)
{
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
case 3:
case 4:
Console.WriteLine("Three or Four");
break;
default:
Console.WriteLine("Out Of Range");
break;
}
Three or Four
좀 더 특별한 것은 데이터의 형식으로도 분기가 가능하다는 점이다.
bool condition = false;
object obj = null;
if(condition)
obj = 4;
else
obj = 4.5f;
switch (obj)
{
case int i:
Console.WriteLine($"{i} is int");
break;
case float f:
Console.WriteLine($"{f} is float");
break;
default:
Console.WriteLine("Out Of Range");
break;
}
4.5 is float
이때 주의할 점은 int i 처럼 데이터 형식 오른쪽에 식별자를 반드시 붙여줘야 한다.
마지막으로 case문에서도 when절을 이용해 분기 할 수 있는 예제를 보자.
bool condition = false;
object obj = null;
if(condition)
obj = 4;
else
obj = 4.5f;
switch (obj)
{
case int i:
Console.WriteLine($"{i} is int");
break;
case float f when f >= 0f:
Console.WriteLine($"{f} is positive float");
break;
case float f:
Console.WriteLine($"{f} is negative float");
break;
default:
Console.WriteLine("Out Of Range");
break;
}
4.5 is positive float
'etc > C#' 카테고리의 다른 글
[C#] Lambda Function Capture (1) | 2021.07.30 |
---|---|
[C#] 문자열 보간(Interpolation) (0) | 2021.07.15 |
[C#] Property(프로퍼티), C#만의 특별한 기능 (0) | 2021.07.13 |
[C#] Null-Safety를 지원하는 C# (0) | 2021.07.13 |
[C#] Lambda Expression(람다 식) 이란? (0) | 2021.07.12 |