프로그래밍/C#
[C#] Switch
이내내
2022. 12. 20. 09:57
C# 에서 Switch를 쓰는 방법을 알아봅니다.
선택문인 switch 문은 값에 따라 다양한 제어를 처리할 수 있습니다. 조건을 처리할 내용이 많은 경우 유용합니다.
switch, case, default 키워드를 사용하여 조건을 처리할 수 있습니다.
using System;
namespace Switch
{
internal class Program
{
static void Main(string[] args)
{
Console.Write("정수 1, 2, 3 중에 하나를 입력하시오: ");
int switchNumber = 0;
int.TryParse(Console.ReadLine(), out switchNumber);
switch(switchNumber)
{
case 1:
Console.WriteLine("1을(를) 입력했습니다.");
break;
case 2:
Console.WriteLine("2을(를) 입력했습니다.");
break;
case 3:
Console.WriteLine("3을(를) 입력했습니다.");
break;
default:
Console.WriteLine("처리하지 않은 예외 입력입니다.");
break;
} // switch
} // Main
} // Program
} // Switch
여기서,
case 절에서 break 문을 생략하면,
case 레이블에서 다른 case 레이블로 제어를 이동할 수 없는 것에 대한 에러가 발생합니다.
예외로 case 안에 Statement가 없으면 break가 없어도 에러가 발생하지 않습니다.
아래와 같이 사용할 수도 있지만 추천하지 않음 (goto case 3)
switch (switchNumber)
{
case 1:
Console.WriteLine("1을(를) 입력했습니다.");
goto case 3;
case 2:
case 3:
Console.WriteLine("3을(를) 입력했습니다.");
break;
default:
Console.WriteLine("처리하지 않은 예외 입력입니다.");
break;
} // switch