Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer.
· Encapsulating the method's call from caller.
· Effective use of delegate improves the performance of application.
· Used to call a method asynchronously.
· You can use delegates without parameters or with parameter list.
· You should follow the same syntax as in the method.
(If you are referring to the method with two parameters and return type, the delegate whom you are declaring should be in the same format. This is why it is referred to as type safe function pointer.)
Sample Program using Delegate
Here I have used a small program which demonstrates the use of delegate.
The delegate "
" is declared with double return type and accepts only two integer parameters.
Inside the class, the method named
is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)
method, the delegate instance is created and the function name is passed to the delegate instance as follows:
After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:
Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.
It is a delegate which holds the reference of more than one method.
Multicast delegates must contain only methods that return
, else there is a run-time exception.
Simple Program using Multicast Delegate
In the above example, you can see that two methods are defined named
which take two integer parameters and return type as
In the main method, the
object is created using the following statement:
is added using the
operator and removed using the