2. What is Delegates?
A delegate is an object which refers to a method or we can say it is a
reference type variable that hold a reference to the methods. The
reference can be changed at runtime.
Execution Delegates
Function 1
Function 2
3. About Delegates
• Delegates are the library class in System namespace.
• Delegates are the type-safe pointer of any method.
• Delegates can be chained together as two or more methods can be
called on a single event.
• It doesn’t care about the class of the object that it references.
• Delegates can also be used in “anonymous methods” invocation.
• Provides a good way to encapsulate the methods.
4. Declaration of Delegates
Delegates types are declared with the delegate keyword. They can
appear either on their own or nested within a class.
[modifier] delegate [return_type] [delegate_name] ([parameters]);
5. Delegate Instances
A delegate object is created with the help of new keyword. Once a
delegate is instantiated, a method call made to the delegate is pass by
the delegate to that method.
6. Combining Delegates
When Delegate takes reference with multiple methods then it is called
multicast delegate.
• All methods are called in First in First Out(FIFO) order.
• ‘+’ or ‘+=’ Operator is used to add the methods to
delegates.
• ‘–’ or ‘-=’ Operator is used to remove the methods from
the delegates list.
7. Generic Delegate
Generic Delegate was introduced in .NET 3.5 that don't require to
define the delegate instance in order to invoke the methods.
There are three types of generic delegates:
• Func
• Action
• Predicate
8. Func Delegate
Func is a generic delegate, it is defined under System namespace.
• It can contain minimum 0 and maximum of 16
input parameters.
• The last parameter considered as return type
9. Action Delegate
Action delegate is an in-built generic type delegate. It can contain
minimum 1 and maximum of 16 input parameters and does not contain
any output parameter.
10. Predicate Delegate
A Predicate delegate is an in-built delegate. This delegate takes only
one input and returns the value in the form of true or false.
11. Use case of Delegates
• At event driven design pattern is used.
• It is desirable to encapsulate a static method.
• The caller has no need to access other properties, methods, or
interfaces on the object implementing the method.
• A class may need more than one implementation of the method.