확장 메서드(Extension Method)는 정적(static) 메서드이지만, 마치 해당 타입의 인스턴스 메서드인 것처럼 호출할 수 있는 특별한 메서드입니다.
확장 메서드를 활용하면 새로운 파생 클래스를 만들거나, 원본 타입을 다시 컴파일하거나 수정하지 않고도 기존 타입에 새로운 메서드를 손쉽게 추가할 수 있습니다.
확장 메서드 작성 방법
다음은 문자열을 정수로 변환하는 확장 메서드 예제입니다. 첫 번째 매개변수 앞에 this 키워드를 붙이면 해당 타입에 대한 확장 메서드가 됩니다.
public static int myExtensionMethod(this string str) {
return Int32.Parse(str);
}예제
아래 예제에서는 string 타입에 확장 메서드를 정의하고, 이를 실제로 호출하는 방법을 보여줍니다.
using System;
using System.Text;
namespace Program {
public static class Demo {
public static int myExtensionMethod(this string str) {
return Int32.Parse(str);
}
}
class Program {
static void Main(string[] args) {
string str1 = "565";
int n = str1.myExtensionMethod();
Console.WriteLine("Result: {0}", n);
Console.ReadLine();
}
}
}실행 결과
Result: 565
위 코드에서 str1.myExtensionMethod()는 일반적인 인스턴스 메서드처럼 보이지만, 실제로는 Demo라는 정적 클래스에 정의된 확장 메서드입니다. 이처럼 확장 메서드를 사용하면 기존 타입의 소스 코드를 변경하지 않고도 원하는 기능을 자연스럽게 추가할 수 있어 코드의 가독성과 재사용성이 크게 향상됩니다.