Have you ever thought about using method as a parameter? Having ability to invoke multiple methods with one command? Delegates can make those ideas reality .
All delegates are implicitly derived from the System.Delegate class. Here is basic structure of delegates:
delegate <return type> <delegate-name> <parameter list>
Delegate syntax is very similar to the method syntax, i takes list of parameters and have return type. Important thing to consider is that all methods passed to delegate must have the same structure, number and type of parameters and return type. Lets take a look at example:
private delegate int Calculator(int n);
public static int AddNum(int p)
We can see that both methods have the same return types and takes the same parameters.
Let's move on to the Practical example.
using System; // Here is our delegate takes int and returns int private delegate int Calculator(int n); class Calculator { //Initial value static int num = 5; //Creating methods //All methods must have the same structure public static int AddNum(int p) { num += p; return num; } public static int MultNum(int q) { num *= q; return num; } public static int SubctNum(int q) { num -= q; return num; } public static int getNum() { return num; } //Calling the main function static void Main(string[] args) { //create delegate instances Calculator c1 = new Calculator(AddNum); Calculator c2 = new Calculator(MultNum); Calculator c3 = new Calculator(SubctNum) //We can connect multiple delegates to execute them together c1 += c2; c1 += c3; //We can also delete reference c -= c3; // Lets call our delegate c(2); Console.WriteLine("Value of Num: {0}", getNum()); Console.ReadKey(); } }
Try this on your compiler see the result.
We just created simple Calculator application that can perform multiple operations with just one call of delegate. This is just the beginning of endless possibilities. Methods can be simplified to shorter versions aka "lambda expressions". Try to remember "+=" operator, we will come back to this while we will talk about events, but this is subject for another post. Stay Awesome.