확장 메서드(Extension Method) 는 기존 클래스의 소스 코드를 수정하지 않고도 새로운 메서드를 추가할 수 있도록 해주는 기능이다.
주로
static클래스와this키워드를 사용하여 구현한다.
static 메서드로 구현된다.Select(), Where() 등)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() 메서드를 추가한 것처럼 사용이 가능하다.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() 메서드를 추가한 것처럼 사용 하다.확장 메서드의 핵심
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()라는 새로운 메서드를 추가한 것처럼 사용 가능하다.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() 메서드를 추가하여 모든 요소를 출력할 수 있도록 확장한다.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() 메서드를 추가하여 나이를 계산할 수 있도록 확장!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 출력
}
}
| 확장 메서드 | 정적 메서드 | |
|---|---|---|
| 호출 방식 | 인스턴스 메서드처럼 호출 (obj.MyMethod()) | Class.MyMethod(obj) 형식으로 호출 |
| 확장 대상 | 기존 클래스에 추가 가능 | 새 클래스를 만들어야 함 |
| 상속 필요 여부 | 상속 없이 확장 가능 | 클래스를 수정해야 가능 |
| 예제 | "hello".WordCount() | StringExtensions.WordCount("hello") |
확장 메서드는 원래 클래스의 멤버가 아니다.
private 필드에는 접근할 수 없다.| 개념 | 설명 |
|---|---|
| 확장 메서드(Extension Method) | 기존 클래스에 새로운 메서드를 추가하는 기능 |
| 정의 방식 | static 클래스 + static 메서드 + this 키워드 |
| 주요 특징 | 기존 클래스를 수정하지 않고도 기능 추가 가능 |
| 대표 예제 | string.WordCount(), DateTime.GetAge() |
| 활용 예시 | List<T>, IEnumerable<T>, DateTime, int 확장 가능 |
| 주의할 점 | 기본 메서드와 충돌 가능, private 멤버 접근 불가 |
즉, 확장 메서드를 사용하면 기존 코드를 수정하지 않고도 기능을 추가할 수 있다!