C# | Delegates
A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered.
KeyPoints About Delegates:
1. Provides a good way to encapsulate the methods.
2. Delegates are the library class in System namespace.
3. These are the type-safe pointer of any method.
4. Delegates are mainly used in implementing the call-back methods and events.
5. Delegates can be chained together as two or more methods can be called on a single event.
6. It doesn’t care about the class of the object that it references.
7. Delegates can also be used in “anonymous methods” invocation.
8. Anonymous Methods(C# 2.0) and Lambda expressions(C# 3.0) are compiled to delegate types in certain contexts. Sometimes, these features together are known as anonymous functions.
Declaration of Delegates (Single Cast Delegate)
Step 1 Declare : Delegate type can be declared using the delegate keyword.
Step 2 Refer Method: Once a delegate is declared, delegate instance will refer and call those methods whose return type and parameter-list matches with the delegate declaration.
Complete Example (Single Cast Delegate)
Multicasting of a Delegate
Multicasting of delegate is an extension of the normal delegate(sometimes termed as Single Cast Delegate). It helps the user to point more than one method in a single call.
Properties of Multicasting:
Delegates are combined and when you call a delegate then a complete list of methods is called.
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.
Multicasting of delegate should have a return type of Void otherwise it will throw a runtime exception. Also, the multicasting of delegate will return the value only from the last method added in the multicast. Although, the other methods will be executed successfully.