O'Reilly logo

Programming Visual Basic .NET, Second Edition by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required