A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
Delegate types are
All C# delegates have multicast capability, this means a single delegate instance can reference more than one target method. You can add or remove target methods using operators
-=. Target methods are called in the order they were added to the delegate instance.
- Create the delegate
delegate void NumbersDelegate(int a, int b);
- Create methods the delegate will call, the need to have the same return type and parameters signature.
public class Foo
- Use the delegate with one method
var foo = new Foo();
- Multicast the delegate to have more than one target
numbersDelegate += foo.MultiplyNumbers;
- You can also remove targets from the delegate
numbersDelegate -= foo.MultiplyNumbers;
This was used in my windows event logger application.
- Create the delegate representing a method
public delegate void EventLogReaderDelegate(EventRecord record);
- Create the methods the delegate will point to
private void Count(EventRecord record)
- Create a method that accepts the delegate as a parameter
private void ProcessReader(EventLogReader reader, EventLogReaderDelegate delegate)
ProcessReaderand pass it the delegates as parameters
public List<EventLogModel> Go()
Similar example from SO: https://stackoverflow.com/questions/2019402/when-why-to-use-delegates