Delegates are one of the most used features of C#. It allows you to pass a function as of function pointer. It is kind of same as function pointer of C++.
Put simply, delegates are the same as a function pointer of C ++. It refers to another function.
As noted in Microsoft official documentation:
“A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.”
Before get deeper into technical jargon about delegates, let us create first a delegate.
Let us talk through the above code.
- Just before main function in comment #1, we are declaring a delegate named AddDelegate. The signature of a delegate is very important, because a delegate can only refer functions matching the same signature.
- We created delegate with return type set to integer and it takes two input integer parameters.
- In comment # 2, we are instantiating delegate and passing add function as reference.
- In comment # 3 invoking the delegate.
On running above, you should get output as shown in the below image:
One important thing you need to keep in mind is that the signature of delegates must match with the signature of the function pointed by the delegate. Not only signature, but also return type should match.