BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Events

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.

Creating a Custom EventArgs Class

New classes for passing event arguments should inherit from EventArgs. Inheritance is beyond the scope of this article and will be explained later in the tutorial. However, to show the use of event arguments we will create such a class for the speeding car example.

To begin, create a new class file containing a class named SpeedEventArgs. To indicate that the class is derived from EventArgs, the base class name is added after the new class's name with the two separated by a colon (:). The new class requires a single property that holds the excess speed for cars travelling faster than their safe speed. The final code for the class is therefore:

public class SpeedEventArgs : EventArgs
{
    private int _excessSpeed;

    public int ExcessSpeed
    {
        get
        {
            return _excessSpeed;
        }
        set
        {
            _excessSpeed = value;
        }
    }
}

To use the event arguments with our existing event, several modifications need to be made. Firstly, the delegate for the event must be updated to replace EventArgs with SpeedEventArgs as follows:

public delegate void SpeedLimitExceededEventHandler(object source, SpeedEventArgs e);

The OnSpeedLimitExceeded method's signature needs to be updated to use the new type:

public virtual void OnSpeedLimitExceeded(SpeedEventArgs e)

Next the call to the OnSpeedLimitExceeded needs to be modified. The Accelerate method will now calculate the difference between the car's current speed and the safety speed. This will be assigned to the event argument property so that it can be passed to subscribing methods. The updated Accelerate method is as follows:

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

    if (oldSpeed <= _safetySpeed && _speed > _safetySpeed)
    {
        SpeedEventArgs e = new SpeedEventArgs();
        e.ExcessSpeed = _speed - _safetySpeed;
        OnSpeedLimitExceeded(e);
    }
}

Finally, the subscribing method's signature within the Program class must be updated to accept the new event arguments and react accordingly:

static void CarSpeedLimitExceeded(object source, SpeedEventArgs e)
{
    Car car = (Car)source;
    Console.WriteLine("Speed limit exceeded by {0}mph", e.ExcessSpeed);
}

These changes mean that the excess speed is now reported by the event itself. As there is no requirement for the program to know what the car's safety limit is, this provides a good example of encapsulation. Execute the program to see the new results.

3 February 2008