C# program to demonstrate the example of multicast delegate

Here, we are going to learn about the multicast delegate and its C# implementation. By Nidhi Last updated : April 03, 2023

C# Example of Multicast Delegate

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

C# code for multicast delegate

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.

C# Delegate Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.