what is delegate:-

  1. A delegate is like a pointer to a function. 
  2. It is a reference type data type and it holds the reference of a method. 
  3. All the delegates are implicitly derived from System.Delegateclass.
  4. A function can have one or more parameters of different data types, but to pass a function as a parameter, delegate is used

  Syntax:- 



     A delegate can be declared using delegate keyword followed by a function signature as       shown below.
Delegate Syntax:
          <access modifier> delegate <return type> <delegate_name>(<parameters>)

   E.g:-
        public delegate void Print(int value);

Example: C# delegate

class Program
{
    // declare delegate
    public delegate void Print(int value);

    static void Main(string[] args)
    {
        // Print delegate points to PrintNumber
        Print printDel = PrintNumber;
       
        // or
        // Print printDel = new Print(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);
    }
}

Comments

Popular posts from this blog

JWT - Token based authentication