Delegates in C# are used to hold a reference to a method.
public delegate int PerformCalculation(int x, int y);
Above, you can see the definition of a delegate. It is used to point to a method which returns integer and takes in two integer parameters.Let's create two methods which are compatible with this delegate.
private static int Add(int x, int y)
{
Console.WriteLine(x + y);
return x + y;
}
private static int Subtract(int x, int y)
{
Console.WriteLine(x - y);
return x - y;
}
Inside of the Main method we'll define two delegates, both of type PerformCalculation, point them to the Add and Subtract methods and invoke them. public static void Main()
{
PerformCalculation addCalculation = Add;
PerformCalculation subtractCalculation = Subtract;
addCalculation(1, 2);
subtractCalculation(2, 1);
}
We can also use a single delegate to point to multiple methods and invoke them all at once. PerformCalculation allCalculations = addCalculation + subtractCalculation;
allCalculations(2, 1);