Using Events and Delegates Together

103 Console.WriteLineThe value of MyData is {0}., FormatMyData End Sub Public Sub DoSomething ... producer.DoSomething ... End Sub End Class The result of calling the EventConsumer classs DoSomething method is: Received the AnotherEvent event. The value of MyData is 42.

2.20.1 Using Events and Delegates Together

Under the covers, .NET uses delegates as part of its events architecture. Delegates are necessary in this architecture because they enable hooking up the consumer classs event-handler method to the event producer recall that delegates encapsulate method invocation. The Visual Basic .NET compiler hides the details of this mechanism, quietly creating delegates as needed under the surface. However, the programmer is free to make this process explicit. The following definition of the EventProducer class is semantically equivalent to the previous one: Public Class EventProducer Public Delegate Sub SomeDelegateByVal MyData As Integer Public Event AnotherEvent As SomeDelegate Public Sub DoSomething ... RaiseEvent AnotherEvent42 ... End Sub End Class Note here that the declaration of SomeDelegate defines a delegate capable of wrapping any subroutine whose signature matches the signature given in the declaration. The subsequent declaration of AnotherEvent defines an event that will use the signature defined by SomeDelegate. Regardless of which syntax is being used, events are actually fields whose type is some delegate type. Variations in syntax are possible on the consumer side, too. When the WithEvents and Handles keywords are used, Visual Basic .NET creates a delegate that wraps the given handler method and then registers that delegate with the object and event given in the Handles clause. The WithEvents and Handles keywords can be omitted, and the delegate declaration and hookup can be done explicitly, as shown here: Public Class EventConsumer Private producer As EventProducer Public Sub New producer = New EventProducer AddHandler producer.AnotherEvent, _ New EventProducer.SomeDelegateAddressOf producer_AnotherEvent End Sub 104 Public Sub producer_AnotherEventByVal MyData As Integer Console.WriteLineReceived the AnotherEvent event. Console.WriteLineThe value of MyData is {0}., FormatMyData End Sub Public Sub DoSomething ... producer.DoSomething ... End Sub End Class The hookup of the handler method to the event producer is done with this statement in the EventConsumer classs constructor: AddHandler producer.AnotherEvent, _ New EventProducer.SomeDelegateAddressOf producer_AnotherEvent The AddHandler statement and its companion, the RemoveHandler statement, allow event handlers to be dynamically registered and unregistered. The RemoveHandler statement takes exactly the same parameters as the AddHandler statement.

2.21 Standard Modules