Good judgement comes from experience, and experience comes from bad judgement. --Fred Brooks

Delegate Syntax and Usage in C#


How do I create a delegate in C#?

Delegate Type Declaration in C#

// simple delegate type declaration
public delegate void MessageHandler(string message);

// with various input parameters
public delegate int CountDaysHandler(CountMethod method, DateTime startDate, DateTime endDate)

Delegate Method Definition in C#

// Defining the delegate

public void HandleMessage(string message)
   // do something with the message

public int CountDays(CountMethod method, DateTime startDate, DateTime endDate)
   // return the number of days between the dates using the desired technique
   return -1;

// Define the delegate as an event
public class MyClass
   public event MessageHandler OnMessage;

Instantiate and Assign the Delegate

// declare a new MessageHandler delegate
private MessageHandler _MyMessageHandler = new MessageHandler(HandleMessage);

private CountDaysHandler _MyCounter = new CountDaysHandler(CountDays);

// register a delegate with an event
MyClass.OnMessage += new MessageHandler(HandleMessage);

// un-register
MyClass.OnMessage -= new MesageHandler(HandleMessage);

// View list of registered delgates
Delegate[] delegateList = OnMessage.GetInvocationList();
foreach (Delegate d in delegateList)
   // do something with the delegate