find and solve || findandsolve.com
Please wait.....

Delegates - C#

In C#, A delegate is a type that represents references to methods with a particular parameter list and returns type and is similar to pointers to functions, in C or C++.

In the static method in C# prorgramming language, delegate encapsulates method only. But for instance method, it encapsulates method and instance both.

Internally a delegate declaration defines a class which is the derived class of System.Delegate.


C# Delegate Example

using System;  

delegate int Calc(int number);//declaring delegate
public class DelegateExample
{
    static int number = 1001;
    public static int Add(int number)
    {
        number = number + number;
        return number;
    }
    public static int mul(int n)
    {
        number = number * n;
        return number;
    }
    public static int getNumber()
    {
        return number;
    }
    public static void Main(string[] args)
    {
        Calc objCalc = new Calc(Add);//instantiating delegate
        Calc objCalc1 = new Calc(mul);
        objCalc(20);//calling method using delegate
        Console.WriteLine("After objCalc delegate, Number is: " + getNumber());
        objCalc1(3);
        Console.WriteLine("After objCalc1 delegate, Number is: " + getNumber());
    }
}  

Output

After objCalc delegate, Number is: 1001

After objCalc1 delegate, Number is: 3003