The source code to demonstrate a multicast delegate is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to demonstrate multicast delegate.
using System;
delegate void MyDel(int num1,int num2);
class Sample
{
static void Add(int num1, int num2)
{
Console.WriteLine("\tAddition: "+(num1+num2));
}
static void Sub(int num1, int num2)
{
Console.WriteLine("\tSubtraction: " + (num1 - num2));
}
static void Main()
{
int num1 = 0;
int num2 = 0;
MyDel del = new MyDel(Add);
Console.Write("Enter the value of num1: ");
num1 = int.Parse(Console.ReadLine());
Console.Write("Enter the value of num2: ");
num2 = int.Parse(Console.ReadLine());
del += new MyDel(Sub);
Console.WriteLine("Call 1:");
del(num1, num2);
del -= new MyDel(Sub);
Console.WriteLine("Call 2:");
del(num1, num2);
}
}
Output:
Enter the value of num1: 10
Enter the value of num2: 5
Call 1:
Addition: 15
Subtraction: 5
Call 2:
Addition: 15
Press any key to continue . . .
Explanation:
In the above program, we created a Sample class that contains three static methods Add(), Sub(), and Main() method.
In the Main() method, we read the value of variables num1, num2.
MyDel del = new MyDel(Add);
In the above method, we bind the Add() method to the delegate del.
del += new MyDel(Sub);
Then we also bind the Sub() method to delegate.
Console.WriteLine("Call 1:");
del(num1, num2);
Here delegate del will call both Add() and Sub() methods.
del -= new MyDel(Sub);
Here we removed the method Sub() from the delegate then it will call only the Add() method.
Program:
The source code to demonstrate a multicast delegate is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a Sample class that contains three static methods Add(), Sub(), and Main() method.
In the Main() method, we read the value of variables num1, num2.
In the above method, we bind the Add() method to the delegate del.
Then we also bind the Sub() method to delegate.
Here delegate del will call both Add() and Sub() methods.
Here we removed the method Sub() from the delegate then it will call only the Add() method.
need an explanation for this answer? contact us directly to get an explanation for this answer