Syntax of delegate
- 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:
- using System;
-
- namespace Delegate_Operation
- {
- delegate int Delegate(int x, int y);
-
- class Delegate_Exmaple
- {
- static Delegate dobj = Add;
-
- static int Add(int a, int b)
- {
- return a + b;
- }
-
- static int Sub(int a, int b)
- {
- return a - b;
- }
-
- static int Mul(int a, int b)
- {
- return a * b;
- }
-
- static int Div(int a, int b)
- {
- return a / b;
- }
- static void Main(String[] args)
- {
- int call;
-
- call = dobj.Invoke(5, 5);
- Console.WriteLine("The Sum of {0} + {1} is : {2}",5,5,call);
- Console.WriteLine();
-
- dobj += new Delegate(Sub);
- call = dobj.Invoke(5, 5);
- Console.WriteLine("The Difference of {0} - {1} is : {2}", 5, 5, call);
- Console.WriteLine();
-
- dobj += new Delegate(Mul);
- call = dobj.Invoke(5, 5);
- Console.WriteLine("The Multiplication of {0} * {1} is : {2}", 5, 5, call);
- Console.WriteLine();
-
- dobj += new Delegate(Div);
- call = dobj.Invoke(5, 5);
- Console.WriteLine("The Divition of {0} / {1} is : {2}", 5, 5, call);
-
- Console.ReadKey();
- }
- }
- }
Now deploy this code,so you will get following result
Hope, this example will help you..! Cheers....