C# A delegate is similar to a function pointer in C or C#. A delegate is a reference type variable that holds a reference to a method. References can be changed at runtime.
Syntax for declaring delegates -
delegate <return type> <delegate-name> <parameter list>
Now let’s see how to instantiate a delegate in C#.
After declaring a delegate type, you must use the new keyword to create a delegate object and associate it with a specific method. When you create a delegate, the parameters passed to the new expression are written like a method call, but without the method's parameters.
public delegate void printString(string s); ... printString ps1 = new printString(WriteToScreen); printString ps2 = new printString(WriteToFile);
The following is an example of declaring and instantiating a delegate in C# -
Live Demonstration
using System; delegate int NumberChanger(int n); namespace DelegateAppl { class TestDelegate { static int num = 10; public static int AddNum(int p) { num += p; return num; } public static int MultNum(int q) { num *= q; return num; } public static int getNum() { return num; } static void Main(string[] args) { //create delegate instances NumberChanger nc1 = new NumberChanger(AddNum); NumberChanger nc2 = new NumberChanger(MultNum); //calling the methods using the delegate objects nc1(25); Console.WriteLine("Value of Num: {0}", getNum()); nc2(5); Console.WriteLine("Value of Num: {0}", getNum()); Console.ReadKey(); } } }
Value of Num: 35 Value of Num: 175
The above is the detailed content of How to declare and instantiate delegates in C#?. For more information, please follow other related articles on the PHP Chinese website!