Delegates in C# are the references to the methods, to call the methods indirectly. Delegates holds the address of the method(s); so, it will be easy to call methods through Delegates.
But, why we use Delegates in C# and why can’t we always call methods directly? Good question. But, the answer is simple. As mentioned earlier, Delegates holds an address of a method. Some cases in your program, it may be required to pass methods or functions as arguments. Passing a method or a function as an argument means, passing it’s address. We need an element to hold this address; so, Delegates are useful in this case.
How to declare Delegates in C#?
Below is the syntax to declare the Delegates in C#.
delegate <function-return-type> <delegate-name>(<function-arguments>);
Here, delegate is the keyword in C# and inform to the compiler that this is the Delegate declaration.
- <function-return-type> is the return type of the function whose address is going to assign to the Delegate.
- <delegate-name> is the name of the Delegate name. You have to invoke actual function through this Delegate name.
- <function-argument> is the list of function arguments separated by “,”(comma).
For example:
delegate int SumMethodInvoker(int x, int y);
This is the delegate which holds the reference to a function which has 2 int type arguments and returns an int type value.
Using Delegates in C#
When you are declaring a delegate means, you are declaring a delegate class. To use a delegate, you need to create an instance of it; like the same way as you create an instance of a class to use it.
See the below example:
SumMethodInvoker delSum = new SumMethodInvoker(x.Sum);
- Here we have created an instance delSum for the delegate SumMethodInvoker.
- We need to assign function reference to a delegate. So, we have assigned function address Sum. Sum is a function which is defined in a class whose instance is “x” and the Sum function prototype is same that match with delegate’s prototype.
Once we have an instance for the delegate, we can invoke the associated method through the instance of the delegate.
delSum(x, y);
All together here is the code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeSteps { // -- Program class Program { static void Main(string[] args) { int x = 10; int y = 20; Math objMath = new Math(); // -- Create an instance for delegate SumMethodInvoker delSum = new SumMethodInvoker(objMath.Sum); // -- Usage of the delegate Console.WriteLine("Sum of " + x + " + " + y + " = " + delSum(10, 20)); } } // -- Math class class Math { // -- Sum method public int Sum(int x, int y) { return (x + y); } } // -- Declare a delegate delegate int SumMethodInvoker(int x, int y); }
..