C# - Multicast Delegates

 

In my previous article we discuss about what are the delegates and how to create Singlecast delegate in C#. Today we discuss about what are Multicast delegates and how to create Multicast delegates in C#.

 

As we know for Singlecast delegate we can attach only single method and delegate definition should match with the attached method definition. Whereas in the case of Multicast delegate we can attach multiple methods to delegate. Important thing we have to remember in the case of Multicast delegate is all the methods which are attached to multicast delegate should have same method definition that means all methods should take same number of parameters, same data type, should not return any value and the delegate definition also should match to this. We can execute the list of methods at once by invoking the Multicast  delegate.

 

Open Microsoft Visual Studio => Create Console Application and name it as MultiCastDelegate

 

Create MultiCast delegate and Employee class shown below.

 

using System;

 

namespace MultiCastDelegate

{

    public delegate void ExecuteMethods(string sMethod);

    class Employee

    {

        public void GetCompanyType(string sName)

        {

            Console.WriteLine(sName + " company is IT company");

        }

 

        public void GetCompanyEmployees(string sName)

        {

            Console.WriteLine(sName + " company has 10,000 Employees");

        }

    }

}

 

Now add and execute Employee class methods to delegate ExecuteMethods as shown below.

 

using System;

 

namespace MultiCastDelegate

{

    class Program

    {

        static void Main(string[] args)

        {

            Employee objEmp = new Employee();

 

            ExecuteMethods delObj = new ExecuteMethods(objEmp.GetCompanyType);

            delObj += new ExecuteMethods(objEmp.GetCompanyEmployees);

 

            delObj.Invoke("ABC");

 

            Console.ReadLine();

        }

    }

}

 

As shown above we add the two methods GetCompanyType(), Get CompanyEmployees() methods to delegate ExecuteMethods and executed the delegate by using Invoke() predefined method. As shown above the two methods and delegate method definition is same.

 

Run the application and output is as shown below.

 

           

 

                                                                                                 MultiCastDelegate.zip (23.48 kb)