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

91

The next section will add more logic to the set accessor in CurrentBalance in the next listing and raise an event for the calling code.

Events

An event is a type of class member that allows your class or class instance to notify any other code about things that happen within that class. To help you understand the use of events, this section will associate an event with the accountBalance of an account. Listing 4-1 is a modified version of Listing 3-8 from Chapter 3. It additionally has an event and logic that raises the event.

To see how an event can be useful, consider a program that uses a class that manages accounts. There could be different types of accounts, such as checking or savings. If a customer performs an overdraft, the consequences probably vary by what type of account is being used. However, all you want is a generalized account class that can be used by any bank account type and doesn’t know what the overdraft rules are, which makes the class more reusable in different scenarios. Therefore, you can give the account class an event that will fire off a notification whenever an overdraft occurs. Then, within your specialized checking account class instance, for example, you can register something called an event handler so that the instance of the class knows each time the overdraft event occurs via the handler.

In Listing 4-1, the CurrentBalance property is modified to raise (or fire off) an OverDraft event whenever the assigned value is less than 0. The Main method hooks up another method that will run whenever that event occurs. I’ll explain the event first and then follow up with a discussion of how to hook up a method that listens for when the event is raised and receives the message sent by the event.

Listing 4-1 Event demo

C#:

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

namespace FirstProgram

{

class Program

{

private decimal accountBalance = 100m;

static void Main(string[] args)

Page 114
Image 114
Microsoft 9GD00001 manual Events, Listing 4-1 Event demo