Err and err and err again, but less and less and less. --Piet Hein
NinjaTrader Kickstart - Use your dev skills to trade the markets. This is my latest free course. I hope you'll try it out - Steve @ CambiaResearch

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

Version: 5.1.20191022.2156