C# program to demonstrate the example of multicast delegate

Here, we are going to learn about the multicast delegate and its C# implementation.
Submitted by Nidhi, on September 15, 2020

Here we will create a multicast delegate. The multicast delegate holds the reference of multiple methods.

Program:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.