Understanding and using delegates in C# - Part I
Delegate is a type that defines a method signature. It is also an object that receives that method as parameter when constructed and then call's that method to do some operation.
The definition of delegate
// Define delegate
public delegate int MathematicalOperation(int numberA, int numberB);
And that's it! Delegate is defined!
Based on that definition, we create two methods that do the real operations: add's and subtract's two numbers.
The most important things when defining these methods that will be passed to delegate as parameter is that they have:
- same return type
- parameters with same name and type
Operational methods (delegate parameters)
Well, there is nothing mutch to be said in here - these are method's that do two most basic mathematical operation's.
/// <summary>
/// Normal function that ADD's two numbers
/// </summary>
public static int Add(int numberA, int numberB)
{
return numberA + numberB;
}
/// <summary>
/// Normal function that SUBTRACT's two numbers
/// </summary>
public static int Subtract(int numberA, int numberB)
{
return numberA - numberB;
}
Combine DELEGATE & METHODS
And, here is the sample how to use delegates:
static void Main(string[] args)
{
// Instantiate the delegate, and define in constructor which method will be called later...
// Or you can even write: "MathematicalOperation mathOperation = Add;"
MathematicalOperation mathOperation = new MathematicalOperation(Add);
// Call the delegate as object with "mathOperation(3, 5)"
Console.WriteLine(string.Format("Add: {0}", mathOperation(3, 5))); // Add: 8
// Define another method "Subtract" that will be called instead of first one...
mathOperation = new MathematicalOperation(Subtract);
// Call the delegate as object with "mathOperation(4, 9)"
Console.WriteLine(string.Format("Subtract: {0}", mathOperation(4, 9))); // Subtract: -5
// Just pause the app...
Console.ReadKey();
}
This is the most basic sample, how the delegates are defined and used.
In the next article (part II), I will write how the delegates are used in real world situations!