Delegates in C# are type safe function pointers, which hold a reference to one or more methods
that have the same signature as that of a signature of a delegate.
Delegates are similar to functions pointers in C/C++.
Syntax:
delegate
We have 2 Types of Delegates.
- Single Cast Delegates: Delegates that reference a single method.
- Multi Cast Delegates: Delegates who hold reference to more than one method.
Example 1: Single Cast Delegate.
The output will be:
Multicast Delegate:
It is an extension of Single Cast Delegate. We can call more than one method using + operator in a multicast delegate.
- We have created 2 instances of SampleDelegate S1 and S2.
- S1 holds a reference to FirstMethod() and S2 holds a reference to the second method().
- S1+=S2; This statement will make S1 to point to both FirstMethod() as well as SecondMethod();
- Finally we invoke S1() which inturn will invoke both FirstMethod() and SecondMethod()
Example 2: Multi Cast Delegate.
Explanation:
- Two instances of delegates g1 and g2 created which reference to each greet method.
- g1+=g2 is equal to g1=g1+g2 which make g1 point to both methods.
- So g1() invokes both methods.
The output will be: