확장 메서드

Shy·2025년 3월 17일

C#

목록 보기
24/27

확장 메서드(Extension Method)

확장 메서드(Extension Method) 는 기존 클래스의 소스 코드를 수정하지 않고도 새로운 메서드를 추가할 수 있도록 해주는 기능이다.

주로 static클래스와 this키워드를 사용하여 구현한다.

  • 기존 클래스의 소스 코드 변경 없이 새로운 메서드를 추가할 수 있다.
  • 인스턴스 메서드처럼 호출 가능하지만, 실제로는 static 메서드로 구현된다.
  • LINQ (Language Integrated Query)에서 많이 사용된다. (Select(), Where() 등)

1. 확장 메서드 기본 사용법

using System;

static class StringExtensions
{
    // 확장 메서드 정의 (this 키워드를 사용하여 확장할 대상 지정)
    public static int WordCount(this string str)
    {
        return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
    }
}

class Program
{
    static void Main()
    {
        string text = "Hello world, this is C#!";
        Console.WriteLine(text.WordCount()); // 5 출력
    }
}

출력

5
  • 기존 string 클래스에 WordCount() 메서드를 추가한 것처럼 사용이 가능하다.

2. 확장 메서드의 구현 원리

using System;

static class StringExtensions
{
    // 확장 메서드 정의 (this 키워드를 사용하여 확장할 대상 지정)
    public static int WordCount(this string str)
    {
        return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
    }
}

class Program
{
    static void Main()
    {
        string text = "Hello world, this is C#!";
        Console.WriteLine(text.WordCount()); // 5 출력
    }
}

출력

5
  • 기존 string 클래스에 WordCount() 메서드를 추가한 것처럼 사용 하다.

3. 확장 메서드의 구현 원리

확장 메서드의 핵심

  • 확장 메서드는 반드시 static 클래스 내에 static 메서드로 선언해야 한다.
  • 첫 번째 매개변수 앞에 this 키워드를 붙이면 해당 타입의 인스턴스 메서드처럼 사용 가능하다.
public static class MyExtensions
{
    public static int MultiplyByTwo(this int value)
    {
        return value * 2;
    }
}

사용 예제

int number = 5;
Console.WriteLine(number.MultiplyByTwo()); // 10 출력
  • int 타입에 MultiplyByTwo()라는 새로운 메서드를 추가한 것처럼 사용 가능하다.

4. 확장 메서드 활용 예제

(1) List<T> 확장하기

using System;
using System.Collections.Generic;

static class ListExtensions
{
    public static void PrintAll<T>(this List<T> list)
    {
        foreach (var item in list)
        {
            Console.WriteLine(item);
        }
    }
}

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3 };
        numbers.PrintAll(); // 1, 2, 3 출력
    }
}
  • List<T>PrintAll() 메서드를 추가하여 모든 요소를 출력할 수 있도록 확장한다.

(2) DateTime 확장하기

using System;

static class DateTimeExtensions
{
    public static int GetAge(this DateTime birthDate)
    {
        int age = DateTime.Now.Year - birthDate.Year;
        if (DateTime.Now < birthDate.AddYears(age)) age--; // 생일이 아직 안 지났다면 나이 -1
        return age;
    }
}

class Program
{
    static void Main()
    {
        DateTime birthDate = new DateTime(2000, 5, 15);
        Console.WriteLine(birthDate.GetAge()); // 현재 연도 기준 나이 출력
    }
}
  • DateTime 클래스에 GetAge() 메서드를 추가하여 나이를 계산할 수 있도록 확장!

(3) IEnumerable<T> 확장하기 (LINQ 스타일)

using System;
using System.Collections.Generic;
using System.Linq;

static class EnumerableExtensions
{
    public static IEnumerable<T> FilterEven<T>(this IEnumerable<T> source, Func<T, int> selector)
    {
        return source.Where(item => selector(item) % 2 == 0);
    }
}

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
        var evenNumbers = numbers.FilterEven(x => x); // 짝수만 필터링

        Console.WriteLine(string.Join(", ", evenNumbers)); // 2, 4, 6 출력
    }
}
  • LINQ 스타일로 컬렉션을 필터링하는 확장 메서드!

5. 확장 메서드 vs 정적 메서드

확장 메서드정적 메서드
호출 방식인스턴스 메서드처럼 호출 (obj.MyMethod())Class.MyMethod(obj) 형식으로 호출
확장 대상기존 클래스에 추가 가능새 클래스를 만들어야 함
상속 필요 여부상속 없이 확장 가능클래스를 수정해야 가능
예제"hello".WordCount()StringExtensions.WordCount("hello")

6. 확장 메서드의 단점

확장 메서드는 원래 클래스의 멤버가 아니다.

  • 기본 메서드와 이름이 충돌하면, 원래 메서드가 우선 실행된다.
  • private 필드에는 접근할 수 없다.
  • 가독성이 떨어질 수 있다 (어떤 확장 메서드인지 명확하지 않음).

정리

개념설명
확장 메서드(Extension Method)기존 클래스에 새로운 메서드를 추가하는 기능
정의 방식static 클래스 + static 메서드 + this 키워드
주요 특징기존 클래스를 수정하지 않고도 기능 추가 가능
대표 예제string.WordCount(), DateTime.GetAge()
활용 예시List<T>, IEnumerable<T>, DateTime, int 확장 가능
주의할 점기본 메서드와 충돌 가능, private 멤버 접근 불가

즉, 확장 메서드를 사용하면 기존 코드를 수정하지 않고도 기능을 추가할 수 있다!


profile
신입사원...

0개의 댓글