Bits & Bytes

Creating Multicast Delegates in C#

As stated in my prior post on C# delegates, a C# delegate is similar to a function pointer in C++. There, I gave a couple of examples of how to use delegates and said that I would cover multicast delagates later.

So, what is a multicast delegate? A multicast delegate is a function pointer that can be set to point to multiple functions at the same time. It calls each of them in order when it is called. Since a function can only return one value, multicast delegates must return a void type; that is, they must not have a return type.

The program below demonstrates how to use a multicast delegate. First, the delegate type DPrintMultipleOfNumber is declared. Then, inside the Main() function, we declare an instance of the delegate called pfnMulticast and initialize it with function OneTimes() that is defined below the Main() function. The next two lines add the functions TwoTimes() and ThreeTimes() to it via the =+ operator. Finally, we call all three of the functions via the delegate with the argument 13.

The output of the program looks like this:

UsingMulticast

Program.cs

using System;

namespace UsingMulticastDelegates {
    class Program {

        delegate void DPrintMultipleOfNumber(double dX);

        static void Main(string[] args) {
            DPrintMultipleOfNumber pfnMulticast = OneTimes;
            pfnMulticast += TwoTimes;
            pfnMulticast += ThreeTimes;
            pfnMulticast(13);
        }

        static void OneTimes(double dX) {
            Console.WriteLine("One times {0} is {1}", dX, dX);
        }

        static void TwoTimes(double dX) {
            Console.WriteLine("Two times {0} is {1}", dX, 2.0*dX);
        }

        static void ThreeTimes(double dX) {
            Console.WriteLine("Three times {0} is {1}", dX, 3.0*dX);
        }
    }
}

Tags: , , , , , , , , ,

Michael Hall

By: Michael Hall

Leave a Reply

*

 

© 2007–2024 XoaX.net LLC. All rights reserved.