C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.
A delegate can be declared using delegate keyword followed by a function signature as shown below.
The following example declares a Print delegate.
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.
A delegate can be declared using delegate keyword followed by a function signature as shown below.
<access modifier> delegate < return type> <delegate_name>(<parameters>)
The following example declares a Print delegate.
public delegate void Print(int value)
Instantiating Delegates
Once a delegate type is declared, a delegate object must be created with the new keyword and be associated with a particular method. When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the arguments to the method.
Example:
class Program
{
// declare delegate
public delegate void Print(int value);
static void Main(string[] args)
{
// Print delegate points to PrintNumber
Print printDel = PrintNumber;
printDel(100000);
printDel(200);
// Print delegate points to PrintMoney
printDel = PrintMoney;
printDel(10000);
printDel(200);
}
public static void PrintNumber(int num)
{
Console.WriteLine("Number: {0,-12:N0}",num);
}
public static void PrintMoney(int money)
{
Console.WriteLine("Money: {0:C}", money);
}
}
Output:
Number: 10,000 Number: 200 Money: $ 10,000.00 Money: $ 200.00Here, we have declared Print delegate that accepts int type parameter and returns void. In the Main() method, a variable of Print type is declared and assigned a PrintNumber method name. Now, invoking Print delegate will in-turn invoke PrintNumber method. In the same way, if the Print delegate variable is assigned to the PrintMoney method, then it will invoke the PrintMoney method.
No comments:
Post a Comment