What are C# delegates? How to declare and instantiate delegates?

What are Delegates in C#?

  • The delegates in C# are same as pointer to functions as in C++ and C.
  • Delegate is the reference kind of variable which is used to hold references to methods.
  • These references could be varied at runtime.
  • The delegates are specially used to implement call-back functions as well as events.
  • All these delegates are derived implicitly form the System.Delegate class.

Declaration of delegates

  • The declaration of delegates is helpful in determining methods that the delegate references.
  • A delegate can either refer to a function that has the similar signature of the delegate.
  • Consider the delegate below for example:    
     public delegate int SampleDelegate (string x); 
  • The delegate that preceed is used for referencing any methods which has string parameter and would return an integer type of variable.
  • Delegate declaration syntax is:
    delegate <return type><delegate-name><parameter list> 

Instantiation of delegates

  • After the delegate gets declared, an object for delegate should be created using ‘new’ as keyword and it must be associated to a particular function.
  • While creating a delegate, the parameter passed to newer expression is coded as like method call, with the only difference being lack of arguments to that method.
  • Example:        

                   public delegate void printS(string x);

                     ...

                    printS px1 = new printS(WriteToFile);

                    printS px2 = new printS(WriteToScreen);

  • The example below illustrates instantiation, declaration and delegate usage which are used in referencing methods with integer parameter and would return an integer as value:

            using System; 

           delegate int NumChange(int a);

           namespace DelegateApp

           {

           class TestingDelegate

           {

           static int number = 15;   

           public static int AddNumber(int b)

           {

           number += b;

           return number; 

           }    

           public static int MultNumber(int c)   

          {   

          number *= c;   

          return number;    

          }

          public static int getNumber()

          {

          return number;

          }  

          static void Main(string[] args)

          {

          //creation of delegate objects 

          NumChange nx1 = new NumChange(AddNum); 

          NumChange nx2 = new NumChange(MultNum); 

          // method calling with the help of delegate objects

          nx1(35);

          Console.WriteLine("Number value is: {0}", getNumber());

          nx2(15);

          Console.WriteLine("Number Value is: {0}", getNumber());        

          Console.ReadLine(); 

          }

          }}

  • Multi-casting of delegates are also allowed in C#.