숏컷 코드
// 타입 패턴 — 타입 확인과 변수 선언을 한 번에
if (shape is Circle c)
Console.WriteLine($"반지름: {c.Radius}");
// switch expression + 관계 패턴
string grade = score switch
{
>= 90 => "A",
>= 80 and < 90 => "B",
>= 70 => "C",
< 0 => throw new ArgumentException(),
_ => "F"
};문법
어떤 패턴이 있나
입문 단계에서는 아래 네 가지를 먼저 익히면 대부분의 분기 코드를 읽을 수 있습니다.
if (obj is string s) { } // 타입 패턴
if (user is { IsAdmin: true }) { } // 프로퍼티 패턴
bool ok = score is >= 0 and <= 100; // 관계 패턴
bool ready = value is not null; // null 패턴- 타입 패턴
- 프로퍼티 패턴
- 관계 패턴
- null 패턴
타입 패턴 (type pattern)
is Type variable 형태입니다. 타입 검사와 변수 선언을 동시에 수행합니다. 검사 성공 시 변수에 이미 캐스팅된 값이 들어 있어 추가 캐스팅이 필요 없습니다.
// ❌ 구식 방식 — 검사 후 다시 캐스팅
if (obj is string)
{
string s = (string)obj;
Console.WriteLine(s.Length);
}
// ✅ 타입 패턴 — 한 번에 처리
if (obj is string s)
Console.WriteLine(s.Length);is null / is not null 패턴도 타입 패턴의 일종으로, == null보다 null 체크 의도가 분명합니다.
프로퍼티 패턴 (property pattern)
{ Property: pattern } 형태로 객체 속성을 분기 조건으로 씁니다. 중첩 객체도 한 번에 분해할 수 있습니다.
if (user is { IsAdmin: true, Name: not null })
{
Console.WriteLine($"관리자: {user.Name}");
}
string discount = order switch
{
{ Customer.IsPremium: true, Total: > 100_000 } => "15%",
{ Customer.IsPremium: true } => "10%",
{ Total: > 50_000 } => "5%",
_ => "0%"
};관계 패턴 (relational pattern)
>, <, >=, <= 를 패턴으로 씁니다. and/or 로 조합할 수 있습니다.
bool isWorkingHour = hour switch
{
>= 9 and < 18 => true,
_ => false
};when 가드
패턴이 맞더라도 추가 조건을 검사해야 할 때 when 을 씁니다.
string result = value switch
{
int n when n % 2 == 0 => "짝수",
int n when n < 0 => "음의 홀수",
int => "양의 홀수",
_ => "정수 아님"
};// ❌ 넓은 패턴을 먼저 두면 아래 arm이 닿지 않는다
string label = value switch
{
int => "정수",
int n when n > 0 => "양수"
};더 복잡한 and/or/not 패턴 조합은 고급 pattern과 list pattern 카드를 참고하세요.
체크포인트
| 패턴 | 예시 | 설명 |
|---|---|---|
| 타입 패턴 | obj is Circle c | 타입 확인 + 변수 선언 |
| null 패턴 | x is null / x is not null | null 검사 |
| 관계 패턴 | >= 90 | 값 범위 비교 |
| 프로퍼티 패턴 | { Name: "Mina" } | 속성 구조로 분기 |
and / or / not | >= 0 and < 100 | 패턴 조합 |
when 가드 | when n % 2 == 0 | 패턴 + 추가 조건 |
주의할 점
패턴 매칭은 "데이터 구조 자체가 분기의 근거"일 때 빛납니다. 반면 절차적 흐름이나 부작용이 중심인 코드라면 전통적인 if/else가 더 읽기 쉬울 수 있습니다.
switch expression의 arm 순서가 중요합니다. 컴파일러는 위에서 아래로 평가하다가 처음 일치하는 arm에서 멈춥니다. 범위가 좁은 조건을 먼저, 넓은 조건(_)을 마지막에 배치하세요.
참고 링크
2 sources