How to instantiate delegates in C#?


Use the new keyword to instantiate a delegate. 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.

For example −

public delegate void printString(string s);
printString ps1 = new printString(WriteToScreen);

You can also instantiate a delegate using an anonymous method −

//declare
delegate void Del(string str);
Del d = delegate(string name) {
   Console.WriteLine("Notification received for: {0}", name);
};

Let us see an example that declare and instantiates a delegate −

Example

 Live Demo

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();
      }
   }
}

Output

Value of Num: 35
Value of Num: 175

Updated on: 22-Jun-2020

814 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements