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
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
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)