기존 클래스를 상속하지 않고 기존 클래스의 내부 구조를 전혀 바꾸지 않고도, 새로운 메서드를 추가할 수 있게 하는 것이 확장 메서드이다.
확장 메서드는 static 클래스 내의 static 메서드로 this 예약어 매개변수를 이용하여 구현한다.
✍ 샘플 코드
class Test
{
static void Main(string[] args)
{
string str1 = null;
string str2 = "";
string str3 = "hi";
Console.WriteLine(str1.IsBlank());
Console.WriteLine(str2.IsBlank());
Console.WriteLine(str3.IsBlank());
}
}
static class Extensions
{
public static bool IsBlank(this string txt)
{
if (txt == null || txt.Equals(""))
return true;
return false;
}
}
✅ 결과
True
True
False
위의 코드에서 C# 컴파일러가 빌드 시 아래와 같이 코드를 변경한다.
Console.WriteLine(Extensions.IsBlank(str1));
Console.WriteLine(Extensions.IsBlank(str2);
Console.WriteLine(Extensions.IsBlank(str3);
확장 메서드를 구현한 예로는 Enumerable 클래스의 Min, Max, Sum, Contain 등의 메서드가 있다. 해당 확장 메서드를 사용하기 위해서는, 이들이 정의되어 있는 namespace System.Linq를 using문으로 선언해야 한다.
✍ 샘플 코드
using System;
using System.Collections.Generic;
using System.Linq;
namespace Pjt
{
class Test
{
static void Main(string[] args)
{
List<int> list= new List<int>() { 1,2,3,4,5 };
Console.WriteLine(list.Min());
}
}
}