기본 패턴
csharp
public static class StringExtensions
{
public static bool IsBlank(this string value)
{
return string.IsNullOrWhiteSpace(value);
}
}
bool empty = "".IsBlank();설명
this키워드를 첫 번째 매개변수 앞에 붙이면 확장 메서드가 됩니다.- 공용 유틸리티 메서드를 읽기 좋은 문법으로 묶을 때 유용합니다.
- LINQ도 extension method를 기반으로 동작합니다.
짧은 예제
csharp
public static int Twice(this int number) => number * 2;
int result = 5.Twice();빠른 정리
| 규칙 | 설명 |
|---|---|
static class | 확장 메서드는 static 클래스 안에 둡니다. |
this Type value | 확장 대상 지정 |
using 필요 | 다른 파일에서는 네임스페이스 import 필요 |
주의할 점
너무 많은 확장 메서드를 여러 곳에 흩어 두면 자동완성 목록이 복잡해지고 어디서 왔는지 찾기 어려워질 수 있습니다.