Software & Finance





C# - Multicast Delegates





Refer to Delegates before reading about multicast delegates.

C# delegates are like pointers in C++ and it does use the word called delegate. The feature with multicast deletgate is that you can assign as many function as you want to a single delegate object and invoking all the function together.

Look at the sample code and it is easy to understand.

 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

namespace Basics

{

    class Drawing

    {

        public delegate void Shape();

 

        public void Rectangle()

        {

            Console.WriteLine("This is Rectangle");

        }

 

        public void Square()

        {

            Console.WriteLine("This is Square");

        }

 

        public void Circle()

        {

            Console.WriteLine("This is Circle");

        }

 

        static void Main(string[] args)

        {

            Drawing d = new Drawing();

 

            // Shape is like a fuction pointer in C++

            // Shape [] is assigned with 3 functions with same function sigature

            Shape [] parray = { new Shape(d.Rectangle),

                                new Shape(d.Square),

                                new Shape(d.Circle)

            };

 

            // Use multicast delegates by adding all the function and the invoke all 3 functions with a single call.

 

               Shape muticastptr = null;

          for (int i = 0; i < 3; i++)

          {

              muticastptr += parray[i];

          }

 

           muticastptr();

        }

}

 

    }

}

Output


 

This is Rectangle

This is Square

This is Circle