How to Create and use Multicast Delegate in C#

Syntax of delegate

  1. Delegate [ data-type ] [ delegate-name] [argument-list]  

Following example demonstrates about Multicasting of a delegate with Arithmatic operations.When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type.

Let see the example:

  1. using System;  
  2.   
  3. namespace Delegate_Operation  
  4. {  
  5.     delegate int Delegate(int x, int y);  
  6.       
  7.     class Delegate_Exmaple  
  8.     {  
  9.        static Delegate dobj = Add;  
  10.       
  11.        static int Add(int a, int b)  
  12.         {  
  13.             return a + b;  
  14.         }  
  15.   
  16.        static int Sub(int a, int b)  
  17.        {  
  18.            return a - b;  
  19.        }  
  20.   
  21.        static int Mul(int a, int b)  
  22.        {  
  23.            return a * b;  
  24.        }  
  25.   
  26.        static int Div(int a, int b)  
  27.        {  
  28.            return a / b;  
  29.        }  
  30.         static void Main(String[] args)  
  31.        {  
  32.             int call;  
  33.   
  34.             call = dobj.Invoke(5, 5);  
  35.             Console.WriteLine("The Sum of {0} + {1} is : {2}",5,5,call);  
  36.             Console.WriteLine();  
  37.   
  38.             dobj += new Delegate(Sub);  
  39.             call = dobj.Invoke(5, 5);  
  40.             Console.WriteLine("The Difference of {0} - {1} is : {2}", 5, 5, call);  
  41.             Console.WriteLine();  
  42.   
  43.             dobj += new Delegate(Mul);  
  44.             call = dobj.Invoke(5, 5);  
  45.             Console.WriteLine("The Multiplication of {0} * {1} is : {2}", 5, 5, call);  
  46.             Console.WriteLine();  
  47.   
  48.             dobj += new Delegate(Div);  
  49.             call = dobj.Invoke(5, 5);  
  50.             Console.WriteLine("The Divition of {0} / {1} is : {2}", 5, 5, call);  
  51.   
  52.             Console.ReadKey();  
  53.         }  
  54.     }  
  55. }  

Now deploy this code,so you will get following result

 

Hope, this example will help you..! Cheers....