Chapter 4: Learning Just Enough C# and VB.NET: Intermediate Syntax

93

Console.ReadKey()

End Sub

Public Event OverDraft As EventHandler

Public Sub AccountOverdraft (ByVal sender As Object, ByVal e As EventArgs)

Console.WriteLine("Overdraft Occurred") End Sub

End Module

Listing 4-1 has an event named OverDraft. The OverDraft event is public and is declared with the event keyword. The EventHandler is a delegate, which we’ll discuss soon, but it basically allows you to define the type of method that can be called by the event. It defines the communication contract that must be adhered to by any code that wishes to listen for the event to fire.

Look at the set accessor of the CurrentBalance property, inside of the if statement where it determines if value is less than 0. The C# example has another if statement to see if the OverDraft event is equal to null.

In C# when an event is equal to null, it means that nothing has subscribed to be notified by the event—in essence, no other code is listening. However, when the C# event is not null, then this indicates that some code somewhere has hooked up a method to be called when the event fires. That method is said to be listening for the event. So, assuming that the caller has hooked up a method, the OverDraft event is fired. This check for null is important. If nothing is listening for the event (and our code knows this to be the case when the event is null), and we raise or fire the event by calling OverDraft(this, EventArgs.Empty), an error (null reference exception) would occur at runtime whenever a value is set into the CurrentBalance property. The arguments to the C# event mean that the current object (which is the Program class instance), this, and an empty EventArgs will be passed as the event message to any other methods that were hooked up to this event. It is interesting to note that many methods can be hooked up to your event (or none at all), and each will be notified in turn when your event fires. You should start to see that events really are a form of almost spontaneous communication within your program.

In VB, you don’t need to check for Nothing (equivalent to C# null).

The preceding discussion talked about a method that is hooked up to the event and executes (receives a message) whenever the event fires. The next section explains how to use a delegate to specify what this method is.

Page 116
Image 116
Microsoft 9GD00001 manual Learning Just Enough C# and VB.NET Intermediate Syntax