A Delegate is an object that can hold the address of a
method.
A Delegate object can refer only those methods whose signature matches with the Delegate type.
Creating Delegate Types
Delegate types in C# can be created as below:
public delegate void Add(int number1, int number2);
In the above example Add is the Delegate type and a Delegate object of this type can refer any method that matches the signature of this Delegate type.
Initializing a Delegate
A Delegate object can be initialized by referring a method with a matching signature.
In the below example a method called as AddNumbers with matching signature is created. Then a Delegate object calculate of type Add is initialized with the address of method AddNumbers.
public delegate void Add(int number1, int number2);
private static void AddNumbers(int firstNumber, int secondNumber)
{
Console.WriteLine(firstNumber + secondNumber);
}
static void Main(string[] args)
{
//Delegate initialized
Add calculate = AddNumbers;
Console.ReadLine();
}
| Delegates in C# are like function pointers used in C and C++.
|
---|