278
LESSON 23 Defining Classes
}
private void method2Button_Click(object sender, EventArgs e)
{
method2();
}
private void method3Button_Click(object sender, EventArgs e)
{
method3();
}
This isn’t an extremely practical program, and it’s hard to imagine a situation where you would just
want buttons to invoke different delegate instances. This example is just much simpler than many
that use delegates.
Event Handler Delegates
Now that you know a bit about delegates, you can learn how to use them to make an event.
First, in the class that will raise the event, declare a delegate type to define the event handler. Usually
developers end the delegate’s name with
EventHandler to make it obvious what the delegate represents.
By convention, event handlers usually take two parameters named
sender and e. The sender param-
eter is an object that contains a reference to whatever
object is raising the event. The e parameter con-
tains data specific to the event.
The
Turtle class’s OutOfBounds event passes its event handlers an object of type
TurtleOutOfBoundsEventArgs to give them extra information. The following code shows how
the
Turtle class defines this class.
// The TurtleOutOfBoundsEventArgs data type.
public class TurtleOutOfBoundsEventArgs
{
// Where the Turtle would stop if
// this were not out of bounds.
public int X { get; set; }
public int Y { get; set; }
};
The following code shows how the Turtle class declares its OutOfBoundsEventHandler delegate:
// Declare the OutOfBound event’s delegate.
public delegate void OutOfBoundsEventHandler(
object sender, TurtleOutOfBoundsEventArgs e);
Next the class must declare the actual event to tell C# that the class will provide this event. The declara-
tion should begin with an accessibility keyword (
public, private, and so on) followed by the keyword
event. Next it should give the event handler’s delegate type. It finishes with the event’s name.
The following code declares the
OutOfBounds event, which is handled by event handlers of type
OutOfBoundsEventHandler:
// Declare the OutOfBounds event.
public event OutOfBoundsEventHandler OutOfBounds;
596906c23.indd 278 4/7/10 12:33:46 PM