Delegates
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.
Delegates are used to pass methods as arguments to other methods.
Event Handlers are nothing more than methods that are invoked through delegates.
Types of Delegate
Single Delegate - used to invoke single method
Multicast Delegate - used to invoke multiple methods
Generic Delegate
Func Delegate
Action Delegate
Predicate Delegate
Multi-cast Delegate
All the methods will be invoked in the same order as it is added.
If the delegate has return type other than void then the returned value of the last invoked method will be returned.
If the delegate has an out parameter then the value of the out parameter will be the value assigned by the last invoked method.
Generic Delegate
Func Delegate
Func delegate must return a value.
Func delegate can have 0 to 16 input parameters.
Func delegate does not allow ref and out parameters.
Func delegate must have 1 out parameter for the result.
Action Delegate
Action delegate does not return any value.
Action delegate can have 0 to 16 input parameters.
Action delegate does not allow ref and out parameters.
It can be used with Anonymous method and Lambda Expression.
Predicate Delegate
Predicate delegate takes one input parameter and boolean return type.
Anonymous method and Lambda Expressioin can be assigned to Predicate delegate.
Things to Remember
Delegates are like C++ function pointers but are type safe.
Delegates allow methods to be passed as parameters.
Delegates are used in event handling for defining callback methods.
Delegates can be chained together i.e. these allow defining a set of methods that executed as a single unit.
Once a delegate is created, the method it is associated will never changes because delegates are immutable in nature.
Delegates provide a way to execute methods at run-time.
A publisher is an object that contains the definition of the event and the delegate.
Last updated