C# 델리게이트(Delegate)란 무엇인가?
C#에서 델리게이트(delegate)는 메서드에 대한 참조를 담는 특별한 형식입니다. 쉽게 말해, 델리게이트는 메서드의 주소를 저장하는 참조 형식 변수라고 할 수 있으며, 런타임에 참조하는 메서드를 자유롭게 변경할 수 있다는 점이 큰 특징입니다.
델리게이트는 특히 이벤트(event)와 콜백(callback) 메서드를 구현할 때 널리 사용됩니다. 또한 모든 델리게이트는 암묵적으로 System.Delegate 클래스로부터 파생됩니다.
델리게이트 선언 방법
C#에서 델리게이트를 선언하는 기본 문법은 다음과 같습니다.
delegate <반환 형식> <델리게이트 이름> <매개변수 목록>;
델리게이트가 참조할 메서드는 반드시 델리게이트의 반환 형식과 매개변수 목록이 일치해야 합니다.
델리게이트 활용 예제
아래 예제는 하나의 델리게이트를 사용해 콘솔에 출력하는 메서드와 파일에 출력하는 메서드를 상황에 따라 선택적으로 호출하는 방법을 보여줍니다.
using System;
using System.IO;
namespace DelegateAppl {
class PrintString {
static FileStream fs;
static StreamWriter sw;
// 델리게이트 선언
public delegate void printString(string s);
// 콘솔에 출력하는 메서드
public static void WriteToScreen(string str) {
Console.WriteLine("The String is: {0}", str);
}
// 파일에 출력하는 메서드
public static void WriteToFile(string s) {
fs = new FileStream("c:\\message.txt",
FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
// 델리게이트를 매개변수로 받아 필요한 메서드를 호출
public static void sendString(printString ps) {
ps("Hello World");
}
static void Main(string[] args) {
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
sendString(ps1);
sendString(ps2);
Console.ReadKey();
}
}
}코드 설명
printString 델리게이트는 문자열을 매개변수로 받고 반환값이 없는 메서드를 참조할 수 있습니다. Main 메서드에서는 같은 델리게이트 형식으로 WriteToScreen과 WriteToFile 두 메서드를 각각 감싼 후, sendString 메서드에 전달합니다. 이처럼 델리게이트를 매개변수로 넘기면 호출 시점에 실행할 메서드를 유연하게 결정할 수 있습니다.
실행 결과
The String is: Hello World
첫 번째 호출에서는 화면에 문자열이 출력되고, 두 번째 호출에서는 c:\message.txt 파일에 동일한 문자열이 저장됩니다. 이처럼 델리게이트를 활용하면 하나의 인터페이스로 다양한 메서드를 교체하며 호출할 수 있어 코드의 유연성과 재사용성이 크게 향상됩니다.