BlackWaspTM
C# Programming
.NET 1.1+

C# Events (2)

The fifteenth part of the C# Object-Oriented Programming tutorial explains the use of events. Events can be added to a class to allow it to indicate when a specific action has occurred or is about to occur. Subscribers may then react to the event.

Declaring the Event

The event is the publicly visible element of the class. It can be subscribed to by other classes that wish to react to the event being fired. The event is declared by prefixing its name with the event keyword and the name of the delegate that the event will be based upon. To create the event for the Car class, add the following to the class:

public event SpeedLimitExceededEventHandler SpeedLimitExceeded;

Creating an Event Method

An event method is a single method used to raise an event. Although it is not strictly necessary to create such a method, it is advantageous as it makes maintenance of the code simpler and allows derived classes to override the functionality and alter the manner in which events are fired.

To create the event method for the SpeedLimitExceeded event, add the following code to the Car class.

public virtual void OnSpeedLimitExceeded(EventArgs e)
{
    if (SpeedLimitExceeded != null) SpeedLimitExceeded(this, e);
}

There are several items to note in this method. Firstly, the method is marked as virtual. This keyword will be described in detail later in the tutorial. It means that the functionality of this method may be overridden and changed by classes that are derived from the Car class.

The method is named using the name of the event and the prefix 'On'. This is a simple convention that developers expect to see. The event method requires only a single parameter containing the event arguments for the raised event. This parameter holds all of the information that is to be passed to the event subscribers.

Within the method's code block, an if statement checks to see if the event is set to null. This conditional statement checks that there is at least one subscriber to the event as if there are no subscribers, firing the event would cause an exception to be thrown. If the test is passed, the event is raised as if it where a method, passing a reference to the current object and the event arguments that were passed in the parameter.

Calling the Event Method

To complete the sample Car class, the event method needs to be called when the car accelerates past the safety speed. Amend the Accelerate method as follows so that the event is raised when the car's speed changes from below or equal to the safety speed to above it.

public void Accelerate(int mph)
{
    int oldSpeed = _speed;
    _speed += mph;

    if (oldSpeed <= _safetySpeed && _speed > _safetySpeed)
        OnSpeedLimitExceeded(new EventArgs());
}
3 February 2008