Declaring
// 1. Declare it. public delegate int PerformCalculation(int x, int y); public class Person { public string GetName() { return "Mark"; } }So it is like declaring any other type except instead of a variable name, you will be using a method signature. The method name (PerformCalculation) is how you reference the delegate.
You declare the variable "PerformCalculation" as the type "delegate". Think of it as defining a method signature (just like you would in an interface) and then putting the word "delegate" in front of it.
Assigning a Value
public void CreateAndUse() { // 2. Assign a value. PerformCalculation calc = AddNumbers; Person person = new Person(); } public int AddNumbers(int number1, int number2) { return number1 + number2; }See how methods, like AddNumbers, are treated just like objects here? I assign it to my PerformCalculation delegate type. Make sure the signatures are similar.
Using It
// 3. Use it. int sum = calc(1, 2); string name = person.GetName();Remember, your delegate is used to "represent another" method. So when you go to use it, you use it (call it) like a method.
Passing It
Like any object, you can pass it into methods or return it from methods. Here is an example of passing it into a method:
// 4. Pass it. calc = SubtractNumbers; string result = CalculateFreeSpace(calc, person); //... private int SubtractNumbers(int number1, int number2) { return number1 - number2; } private string CalculateFreeSpace(PerformCalculation calc, Person person) { int maxLength = 50; int freeSpace = calc(maxLength, person.GetName().Length); return string.Format("Free Space Left: {0}", freeSpace); }Before I passed as a parameter into the CalculateFreeSpace method, I decided to have it represent a different method with a similar signature.
Pretty interesting, huh? Here, I am injecting customized functionality into the method.
This opens up possibilities to you. You can use this as a way of doing your unit testing. Perhaps the delegate you pass in really calls a SQL Server. So before your unit test calls the method to be tested, you create your delegate to return a hard-coded result instead of calling your SQL Server.
I will be talking more about delegates tomorrow as well.
More Info: MSDN: Delegates