Here I have used a small program which demonstrates the use of delegate.
The delegate "Delegate_add" is declared with int return type and accepts only two integer parameters.
Inside the class, the method named Add is defined with int return type and two integer parameters. (The delegate and method have the same signature and parameter type.)
Inside the Main method, the delegate instance is created and the function name is passed to the delegate instance as follows,
- Delegate_add obj=new Delegate_add(Add);
After this, we are accepting the two values from the user and passing those values to the delegate as we do using method,
Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.
What is Multicast Delegate?
It is a delegate which holds the reference of more than one method.
Multicast delegates must contain only methods that return void, else there is a run-time exception.
Simple Program using Multicast Delegate
- delegate void Delegate_Multicast(int x, int y);
-
- Class Class2
- {
-
- static void Method1(int x, int y)
-
- {
-
- Console.WriteLine("You r in Method 1");
-
- }
-
- static void Method2(int x, int y)
-
- {
-
- Console.WriteLine("You r in Method 2");
-
- }
-
- public static void Main(string[] args)
-
- {
-
- Delegate_Multicast func = new Delegate_Multicast(Method1);
-
- func += new Delegate_Multicast(Method2);
-
- func(1,2);
-
- func -= new Delegate_Multicast(Method1);
-
- func(2,3);
-
- }
-
- }
Explanation
In the above example, you can see that two methods are defined, named method1 and method2, which take two integer parameters and return type as void.
In the main method, the Delegate object is created using the following statement,
- Delegate_Multicast func = new Delegate_Multicast(Method1);
Then the Delegate is added using the += operator and removed using the -= operator.
Dao HuPosted Dec 19, 2016, 1:27 AM
Also can func +=Method2;
Amit Kumar SinghPosted Dec 15, 2016, 11:27 AM
Nice One .................
kalu singh raoPosted Jul 7, 2016, 9:10 AM
Nice...