Multicasting

At times it is desirable to multicast, or call two implementing methods through a single delegate. You accomplish multicasting by encapsulating the various methods in delegates. Then you combine the delegates using the Delegate.Combine( ) shared method. The Combine( ) method takes an array of delegates as a parameter and returns a new delegate that represents the combination of all the delegates in the array.

To see how this works, create a simplistic class that declares a delegate:

Public Class MyClassWithDelegate
    ' the delegate declaration
    Public Delegate Sub StringDelegate(ByVal s As String)
End Class

Then create a class (MyImplementingClass) that implements a number of methods that match the StringDelegate:

Public Class MyImplementingClass

    Public Shared Sub WriteString(ByVal s As String)
        Console.WriteLine("Writing string {0}", s)
    End Sub

    Public Shared Sub LogString(ByVal s As String)
        Console.WriteLine("Logging string {0}", s)
    End Sub

    Public Shared Sub TransmitString(ByVal s As String)
        Console.WriteLine("Transmitting string {0}", s)
    End Sub
End Class

Within the Run( ) method of your Tester class, you’ll instantiate three StringDelegate objects (Writer, Logger, Transmitter):

Dim Writer, Logger, Transmitter As MyClassWithDelegate.StringDelegate

You instantiate these delegates by passing in the address of the methods you wish to encapsulate:

Writer = New MyClassWithDelegate.StringDelegate( _ AddressOf MyImplementingClass.WriteString) Logger = New MyClassWithDelegate.StringDelegate( ...

Get Programming Visual Basic .NET, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.