Quick Reference
switch statement는 matching case에 statements를 실행하고, switch expression은 matching arm의 value를 계산합니다. 둘 다 constant/type/property/relational pattern과 when guard를 지원합니다.
string label = state switch
{
GameState.Ready => "ready",
GameState.Playing => "playing",
null => "missing",
_ => throw new ArgumentOutOfRangeException(nameof(state)),
};
switch (command)
{
case "save": Save(); break;
case "quit": Close(); break;
}- branch 결과를 assign/return하면 expression, statements와 early exit가 중심이면 statement를 씁니다.
- expression은 complete하지 않으면 compiler warning을 낼 수 있고 runtime에서
SwitchExpressionException이 날 수 있습니다. - arm result는 identical type일 필요는 없지만 compiler가 target type 또는 best common conversion을 찾아야 합니다.
- enum의
_fallback은 unknown/future value를 숨길 수 있으므로 fallback policy를 명시합니다.
Statement와 expression
static string DirectionLabel(Direction direction) => direction switch
{
Direction.North => "north",
Direction.South => "south",
_ => "other",
};
static void Move(Direction direction)
{
switch (direction)
{
case Direction.North:
MoveUp();
break;
case Direction.South:
MoveDown();
break;
default:
LogUnknown(direction);
break;
}
}C# switch statement의 non-empty case는 다음 case로 암묵 fall-through할 수 없습니다. 다음 case로 가는 control flow는 break, return, throw, goto case처럼 명시해야 합니다. expression arm은 pattern => expression 형태로 value 하나를 만들며 statement block 전체를 arm으로 둘 수 없습니다.
Pattern, guard, 결과 type
static object Describe(object? value) => value switch
{
null => "missing",
int number when number < 0 => "negative",
int number => number, // arm type이 string과 달라도 object target으로 변환 가능
_ => "other",
};arm은 textual order로 match하며, when guard가 false이면 다음 arm을 검사합니다. 먼저 넓은 pattern을 두면 아래 arm이 unreachable이 될 수 있고 compiler가 diagnostic을 냅니다. null을 받을 수 있는 input에는 null arm 또는 fallback policy를 의도적으로 둡니다.
pattern 자체의 문법과 property/list pattern boundary는 pattern matching 기본과 고급 pattern에서 다룹니다.
완전성과 enum versioning
static string ToLabel(GameState state) => state switch
{
GameState.Ready => "ready",
GameState.Playing => "playing",
GameState.Paused => "paused",
_ => throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown state"),
};switch expression이 input domain을 빠뜨리면 compiler가 non-exhaustive warning을 낼 수 있고, unmatched value가 runtime에 들어오면 SwitchExpressionException이 발생합니다. statement는 matching case가 없으면 default 없이 그냥 다음 statement로 진행합니다.
enum은 compile 뒤에도 cast, deserialization, newer producer 때문에 named member 밖의 underlying value를 받을 수 있습니다. unknown value를 UI "Unknown"으로 허용할지, protocol error로 throw할지, telemetry 후 fallback할지 data boundary의 policy를 정합니다.
자주 틀리는 부분
_ => "other"는 convenient하지만 새 enum member나 invalid external value를 조용히 정상값처럼 처리할 수 있습니다. 안전이 중요한 mapping에는 explicit unknown case 또는 throw policy를 검토하세요.
branch 안에서 I/O·mutation이 많다면 value expression으로 밀어 넣기보다 switch statement 또는 method dispatch가 더 읽기 쉽습니다. expression의 짧음보다 failure path와 side effect가 보이는 것이 우선입니다.
참고 링크
2 sources