First of all, let’s define “What is Delegate?”
We can simply define the delegate as a reference type variable that holds reference to a method.
Delegates are the objects that contain information about the function rather than data.
Now, let’s focus on “Why we use Delegate?”
Delegates are similar to the pointers in C.
We can use delegates whenever we need to pass methods as parameters to another functions so that they can be executed at runtime from there.
We can encapsulate a reference to the method inside the delegate object. One thing to be take care of is that the return type and the signature of delegate should be same as the function we want to encapsulate.
Now coming on the “Advantages of Delegates”
Using delegates, dynamic binding is possible. We can call more than one methods at a time dynamically by calling the delegate in which the methods are defined.
Now let’s create a small console application to understand delegates more thoroughly.
Step 1: First open visual studio, go to New> Project.
Step 2: Now select Console Application. Give a name to the application and press OK.
After project loads, a default class named Program opens. I’m using the same class for creating the demo app. You can create a new class if you want.
So let’s start with coding.
Step 3: Firstly, declare the delegate.
Syntax for delegate declaration is:
Delegate <return type> <delegate name> <parameter list>
Step 4: After declaring the delegate, delegate object must be created and associated with a particular method.
The complete example of delegate declaration, instantiation and use of a delegate that can be used to reference methods is given below:
Here in the example, two functions named SquareRoot and CubeRoot are created, where we are calculating the square root and cube root of a number.
By implementing delegate, we need not to call the functions separately, we just need to define the functions in delegate and when we call the delegate, and functions will automatically be called.
The only thing to keep in mind is that the parameter type, return type and the number of parameters must be same in delegate and functions.
Now after saving, run the application and you can see the result in console window.
This is how we can use delegates in C#. Hope it will be helpful.