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