패턴 매칭은 값의 형식과 형태를 검사해 분기하는 기능입니다. is 키워드와 switch 문/식에서 타입, 상수, 관계, 조합 패턴을 사용할 수 있습니다. 분기 로직을 간결하게 만들고, when 가드로 조건을 정교하게 표현합니다.
1. 개념 설명
타입 패턴은 객체가 특정 타입인지 확인하며 변수로 바인딩합니다. 관계/상수 패턴은 숫자 범위나 특정 값 매칭에 유용합니다. switch 식을 쓰면 매핑 로직을 표현적으로 작성할 수 있습니다.
2. 코드 예제
아래 예제는 is 패턴과 switch 식을 함께 사용해 다양한 입력을 설명합니다.
using System;
class Program
{
static string Describe(object input) => input switch
{
null => "null",
int n when n > 100 => "큰 정수",
int n => $"정수 {n}",
string s when s.Length == 0 => "빈 문자열",
string s => $"문자열 '{s}'",
double d => $"실수 {d:F1}",
_ => "알 수 없음"
};
static string ClassifyRange(int x) => x switch
{
< 0 => "음수",
0 => "영",
<= 10 => "소",
_ => "대"
};
static void PrintPattern(object input)
{
if (input is string s && s.Length > 2)
Console.WriteLine($"긴 문자열: {s}");
else if (input is int n && n % 2 == 0)
Console.WriteLine($"짝수: {n}");
else
Console.WriteLine("다른 값");
}
static void Main()
{
Console.WriteLine(Describe(123));
Console.WriteLine(Describe(""));
Console.WriteLine(Describe(3.14));
Console.WriteLine(Describe(null));
Console.WriteLine(ClassifyRange(0));
Console.WriteLine(ClassifyRange(7));
Console.WriteLine(ClassifyRange(30));
PrintPattern("hello");
PrintPattern(4);
PrintPattern(true);
}
}
출력은 입력 타입과 조건에 따라 다른 설명을 보여줍니다. 패턴 순서가 위에서 아래로 평가된다는 점을 확인해보세요.
3. 주의사항/팁
패턴은 위에서 먼저 매칭되므로 더 구체적인 조건을 앞에 둡니다. 마지막에는 _로 누락 케이스를 처리합니다. C# 8+의 switch 식, 관계 패턴을 쓰려면 최신 컴파일러가 필요합니다. null 처리와 중복 범위에 주의하고, 테스트 케이스로 분기 커버리지를 확인합니다.
'C#' 카테고리의 다른 글
| C# Nullable 참조 타입 (0) | 2026.03.30 |
|---|---|
| C# 레코드 타입 (Record) (0) | 2026.03.27 |
| C# 비동기 프로그래밍 async/await (0) | 2026.03.26 |
| C# LINQ 기초 - Where, Select, OrderBy (0) | 2026.03.26 |
| C# 문자열 보간법 (String Interpolation) (0) | 2026.03.25 |