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 delegate
, Action
and Func
.
Multicast Delegate
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 +=
or -=
. Target methods are called in the order they were added to the delegate instance.
- Create the delegate
1 | delegate void NumbersDelegate(int a, int b); |
- Create methods the delegate will call, the need to have the same return type and parameters signature.
1 | public class Foo |
- Use the delegate with one method
AddNumbers
1 | var foo = new Foo(); |
- Multicast the delegate to have more than one target
1 | numbersDelegate += foo.MultiplyNumbers; |
- You can also remove targets from the delegate
1 | numbersDelegate -= foo.MultiplyNumbers; |
Delegate As A Parameter
This was used in my windows event logger application.
- Create the delegate representing a method
1 | public delegate void EventLogReaderDelegate(EventRecord record); |
- Create the methods the delegate will point to
1 | private void Count(EventRecord record) |
- Create a method that accepts the delegate as a parameter
1 | private void ProcessReader(EventLogReader reader, EventLogReaderDelegate delegate) |
- Call
ProcessReader
and pass it the delegates as parameters
1 | public List<EventLogModel> Go() |
Similar example from SO: https://stackoverflow.com/questions/2019402/when-why-to-use-delegates