C# Delegates
Being a reference to the method, a delegate in C# works like a function pointer in C and C++. As compared to a function pointer, a delegate in C# is objected-oriented, secured and type-safe. Only the method is encapsulated by a delegate in C# for the static method. While, both the method and instance is encapsulated by a delegate in C# for the static method. A delegate is best used as an event. A class is internally defined by a delegate declaration. The defined class is a derived class of the System.Delegate.
Example:
using System; delegate int Calc(int num);//declaring delegate public class Example { static int n = 50; public static int sub(int num) { n = n - num; return n; } public static int mul(int num) { n = n * num; return n; } public static int getnum() { return n; } public static void Main(string[] args) { Calc x = new Calc(sub);//instantiating delegate Calc y = new Calc(mul); x(10);//calling method using delegate Console.WriteLine("After x delegate, Number is: " + getnum()); y(20); Console.WriteLine("After y delegate, Number is: " + getnum()); } } |
Output:
Explanation:
In the above example, we are using the delegate in C# to call the sub() and mul() methods.