Programming/C#
[Programming/C#] switch 문에서 데이터 형식에 따른 조건
scii
2020. 9. 6. 23:51
정수와 문자열 형식 외에도, C# 7.0부터 switch문에 데이터 형식을 조건으로 사용할 수 있게 되었다.
데이터 형식에 따라 분기할 때에는 case 절에서 데이터 형식 옆에 반드시 식별자를 붙여줘야 한다. 선언한 식별자는 case 절 안에서 사용할 수 있다.
또한 when 절을 이용하여 추가적인 조건 검사를 수행할 수 있다. when은 case 절에 붙여 사용한다.
when 절을 if 문과 비슷하다고 생각하면 된다.
using System;
namespace CSharpExam
{
class SwitchExample
{
static int Main(string[] args)
{
object obj = null;
string s = Console.ReadLine();
if (int.TryParse(s, out int out_i))
obj = out_i;
else if (float.TryParse(s, out float out_f))
obj = out_f;
else
obj = s;
switch (obj)
{
case int i:
Console.WriteLine($"{i}는 int");
break;
// obj가 float형식이며 0이상인 경우
case float f when f >= 0:
Console.WriteLine($"{f}는 float이며 양수");
break;
// obj가 float형식이며 0보다 작은 경우
case float f:
Console.WriteLine($"{f}는 float이며 음수");
break;
default:
Console.WriteLine($"{obj}는 모르는 형식");
break;
}
return 0;
}
}
}
/* 결과
3.14
3.14는 float이며 양수
*/