Events
279
The final piece of code that you need to add to the class is the code that raises the event. This code
simply invokes the event handler, passing it any parameters that it should receive.
Before it raises the event, however, the code should verify that some other piece of code has regis-
tered to receive the event. The code does that by checking whether the event is null.
The following code raises the
Turtle class’s OutOfBounds event:
if (OutOfBounds != null)
{
TurtleOutOfBoundsEventArgs args = new TurtleOutOfBoundsEventArgs();
args.X = newX;
args.Y = newY;
OutOfBounds(this, args);
}
If OutOfBounds is not null, this code creates a new TurtleOutOfBoundsEventArgs object, initial-
izes it, and then calls
OutOfBounds, passing it the correct arguments.
A class uses code to decide when to raise the event. The following code shows how the
Turtle class
raises its event when the
Move method tries to move beyond the edge of the Turtle’s Bitmap:
// Make the Turtle move the indicated distance
// in its current direction.
public void Move(int distance)
{
// Calculate the new position.
double radians = Direction * Math.PI / 180;
int newX = (int)(X + Math.Cos(radians) * distance);
int newY = (int)(Y + Math.Sin(radians) * distance);
// See if the new position is off the Bitmap.
if ((newX < 0) || (newY < 0) ||
(newX >= Canvas.Width) || (newY >= Canvas.Height))
{
// Raise the OutOfBounds event, passing
// the event handler the new coordinates.
if (OutOfBounds != null)
{
TurtleOutOfBoundsEventArgs args =
new TurtleOutOfBoundsEventArgs();
args.X = newX;
args.Y = newY;
OutOfBounds(this, args);
}
return;
}
// Draw to the new position.
using (Graphics gr = Graphics.FromImage(Canvas))
{
gr.DrawLine(Pens.Blue, X, Y, newX, newY);
}
// Save the new position.
596906c23.indd 279 4/7/10 12:33:46 PM
280
LESSON 23 Defining Classes
X = newX;
Y = newY;
}
There’s still one piece missing to all of this. The main program must register to receive the
OutOfBound event or it wont know if the Turtle has raised it.
When the Turtle program starts, its
Form_Load event handler executes the following code. This
adds the
Turtle_OutOfBounds method as an event handler for the MyTurtle object’s OutOfBounds
event. Now if the
MyTurtle object raises its event, the program’s Turtle_OutOfBounds event han-
dler executes.
// Register to receive the OutOfBounds event.
MyTurtle.OutOfBounds += Turtle_OutOfBounds;
You can remove an event handler in code like this:
MyTurtle.OutOfBounds -= Turtle_OutOfBounds;
The following code shows the Turtle programs Turtle_OutOfBounds event handler:
// Handle the OutOfBounds event.
private void Turtle_OutOfBounds(object sender, Turtle.TurtleOutOfBoundsEventArgs e)
{
MessageBox.Show(string.Format(“Oops! ({0}, {1}) is out of bounds.”,
e.X, e.Y));
}
TRY IT
In this second Try It in the lesson, you create a
BankAccount class. You give it a Balance property and
two methods,
Credit and Debit. The Debit method
raises an
Overdrawn event if a withdrawal would give
the account a negative balance.
You also build the test application shown in Figure 23-2.
You can download the code and resources for this Try It from the book’s web
page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find
them in the TryIt23b folder in the Lesson23 folder of the download.
FIGURE 232
596906c23.indd 280 4/7/10 12:33:47 PM
Click here to Play
Try It
281
Lesson Requirements
Build the program shown in Figure 23-2.
Create a
BankAccount class. Give it a Balance property.
Add
Debit and Credit methods to add and remove money from the account.
Define the
AccountOverdrawnArgs class to pass to event handlers.
Define the
OverdrawnEventHandler delegate type.
Declare the
Overdrawn event itself.
Make the
Debit method raise the event when necessary.
In the main program, register to receive the
Overdrawn event so it can display a message box.
Hints
This example doesn’t do anything special with the
Balance property so you can make it
auto-implemented.
Make the main form create an instance of the
BankAccount class to manipulate.
Step-by-Step
Build the program shown in Figure 23-2.
1. This is reasonably straightforward.
Create a
BankAccount class. Give it a Balance property.
1. Use code similar to the following:
// The account balance.
public decimal Balance { get; set; }
Add
Debit and Credit methods to add and remove money from the account.
1. Start with code similar to the following. You’ll modify the Debit method later to raise
the
Overdrawn event.
// Add money to the account.
public void Credit(decimal amount)
{
Balance += amount;
}
// Remove money from the account.
public void Debit(decimal amount)
{
Balance -= amount;
}
596906c23.indd 281 4/7/10 12:33:47 PM
282
LESSON 23 Defining Classes
Define the
AccountOverdrawnArgs class to pass to event handlers.
1. Use code similar to the following:
// Dene the OverdrawnEventArgs type.
public class OverdrawnEventArgs
{
public decimal currentBalance, invalidBalance;
}
Define the
OverdrawnEventHandler delegate type.
1. Use code similar to the following:
// Dene the OverdrawnEventHandler delegate type.
public delegate void OverdrawnEventHandler(
object sender, OverdrawnEventArgs args);
Declare the
Overdrawn event itself.
1. Use code similar to the following:
// Declare the Overdrawn event.
public event OverdrawnEventHandler Overdrawn;
Make the
Debit method raise the event when necessary.
1. Modify the simple initial version of the method so it raises the event when necessary.
Use code similar to the following:
// Remove money from the account.
public void Debit(decimal amount)
{
// See if there is enough money.
if (Balance < amount)
{
// Not enough money. Raise the Overdrawn event.
if (Overdrawn != null)
{
OverdrawnEventArgs args = new OverdrawnEventArgs();
args.currentBalance = Balance;
args.invalidBalance = Balance - amount;
Overdrawn(this, args);
}
}
else
{
// There’s enough money.
Balance -= amount;
}
}
In the main program, register to receive the
Overdrawn event so it can display a message box.
1. Use code similar to the following:
// Declare an account.
BankAccount MyAccount;
596906c23.indd 282 4/7/10 12:33:47 PM
Inheritance
283
// Initialize the account.
private void Form1_Load(object sender, EventArgs e)
{
// Initialize the account.
MyAccount = new BankAccount();
MyAccount.Balance = 100M;
// Register to receive the Overdrawn event.
MyAccount.Overdrawn += MyAccount_Overdrawn;
// Display the current balance.
balanceTextBox.Text = MyAccount.Balance.ToString(“C”);
}
// We’re overdrawn.
private void MyAccount_Overdrawn(object sender,
BankAccount.OverdrawnEventArgs args)
{
MessageBox.Show(“Insufcient funds.”);
}
INHERITANCE
Often when you build one class, you end up building a bunch of other closely related classes. For
example, suppose you’re building a program that models your company’s organization. You might
build an
Employee class to represent employees. After a while, you may realize that there are differ-
ent kinds of employees: managers, supervisors, project leaders, and so forth.
You could build each of those classes individually but you’d find that these classes have a lot in
common. They all probably have
FirstName, LastName, Address, EmployeeId, and other proper-
ties. Depending on the kinds of operations you need the objects to perform, you might also find
that they share a lot of methods:
ScheduleVacation, PrintTimesheet, RecordHours, and so
forth. Though you could build each of these classes individually, you would end up duplicating a
lot of code in each class to handle these common features.
Fortunately, C# allows you to make one class inherit from another and that lets them share common
code. When you make one class inherit from another one, you derive the new class from the existing
class. In that case, the new class is called the child class and the class from which it inherits is called
the parent class.
In this example, you could build a
Person class with properties that all people have: FirstName,
LastName, Street, City, State, and Zip. You could then derive the Employee class from Person
and add the new property
EmployeeId.
Next you could derive the
Manager class from Employee (because all Managers are also Employees)
and add new manager-related properties such as
DepartmentName and DirectReports.
Syntactically, to make a class that inherits from another you add a colon and the parent class’s name
after the child class. For example, the following code defines the
Manager class, which inherits
596906c23.indd 283 4/7/10 12:33:47 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.77.171