Delegates in C#

Delgates are similar to a function pointer in C language.

A delegate is an object which stores the reference/address of a function.

A delegate can hold the reference of only those functions whose signature matches with that of a function.

Syntax:

<accessModifier> delegate <datatype> <nameofdelegate>(<arg1>,<arg2>)

There are 2 types of delegates:

  1. Unicast delegate
  2. Multicast delegate

1. Unicast delegate holds the reference of one function.

Example:

  1. using System;    
  2. namespace unicast    
  3. {    
  4.     public delegate int AddDelegate(int x, int y);    
  5.     
  6.     class program    
  7.     {    
  8.         static void Main()    
  9.         {    
  10.             AddDelegate dlg = new AddDelegate(Add);    
  11.             int r = dlg.Invoke(10, 20);    
  12.             Console.WriteLine("Sum is {0}", r);    
  13.             Console.ReadKey();    
  14.         }    
  15.         public static int Add(int x, int y)    
  16.         {    
  17.             return (x + y);    
  18.         }    
  19.     }    
  20. }   
Output:

Sum is 30


2.

 

  • Multicast delegate multicast delegate holds the reference of more than one function.
  • Return type should be void.

Example:

  1. using System;    
  2. namespace multicast    
  3. {    
  4.     public delegate void AddDelegate(int x, int y);    
  5.     
  6.     class program    
  7.     {    
  8.         static void Main()    
  9.         {    
  10.             AddDelegate dlg = new AddDelegate(Add);    
  11.             dlg = dlg + new AddDelegate(Substract);    
  12.            dlg.Invoke(10, 20);    
  13.                 
  14.             Console.ReadKey();    
  15.         }    
  16.         public static void Add(int x, int y)    
  17.         {    
  18.             Console.WriteLine ("Sum is {0}",(x+ y));    
  19.         }    
  20.         public static void Substract(int x, int y)    
  21.         {    
  22.             Console.WriteLine("Difference is {0}", (x - y));    
  23.         }    
  24.     }    
  25. }    
Output:

Sum is 30
Difference is -10 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now