Adding Class Events


Visual Basic .NET Unleashed
By Paul Kimmel
Table of Contents
Chapter 7.  Creating Classes

Adding Class Events

When you want to notify a consumer of your class that something has happened inside your class, you can expose the occurrence as an event:

 Public Event OnText(ByVal Text As String) Private Sub DoText(ByVal Text As String)   RaiseEvent OnText(Text) End Sub 

The LoaderClass (refer to Listing 7.6) raises an OnText event for each line of text read from the input file. The benefit of using events is that the class doesn't need to know which consumers are interested in receiving notification when the event occurs. The LoaderClass code doesn't change regardless of whether any consumer is handling the event.

The statement Public Event OnText(ByVal Text As String) creates a Delegate type implicitly. Any consumer that wants to handle the OnText event raised by the LoaderClass can use a WithEvents statement or an AddHandler statement. Here is an example of an AddHandler statement:

 AddHandler FLoader.OnText, AddressOf OnText 

The object that contains the OnText method (in the preceding statement) is added to the Delegate invocation list of the FLoader.OnText Delegate.

Events aren't polymorphic. That means that we cannot explicitly overload events in child classes. As a general implementation strategy, we can wrap RaiseEvent statements in a method and use the method (see DoText) as a proxy to raise the event. By using a proxy to raise events, we can override the proxy in child classes if we want to change the event-raising behavior.

Event handling has changed significantly in Visual Basic .NET, including the introduction of the Delegate and MulticastDelegate classes that make event handling more powerful. Chapters 8, "Adding Events," and 9 "Understanding Delegates," provide a comprehensive discussion of event handling and delegates.


Visual BasicR. NET Unleashed
Visual BasicR. NET Unleashed
Year: 2001
Pages: 222 © 2008-2017.
If you may any questions please contact us: