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.

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());

Subscribing to an Event

To subscribe to an event, a reference to a method must be added to the event. This is achieved in a similar manner to adding references to a multicast delegate. Each method that is to be called when the event is raised is added to the event using the addition compound assignment operator (+=). The signature of the added methods must match that of the delegate that the event is based upon.

Adding the CarSpeedLimitExceeded Method

In the car example, we will add a new method that captures the event that occurs when a car exceeds the safety speed. This method, named CarSpeedLimitExceeded, is added to the Program class of the console application. It will extract the speed from the source object and output a warning message. The two parameters of the method match the event delegate and will receive the Car object raising the event and the associated event arguments. Add the following method to the Program class:

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

Subscribing to the SpeedLimitExceeded Event

Now that the event has been created and a method exists that will react to the event, we will create a Car object and subscribe to its event. Add the following code to the Main method of the program:

Car car = new Car();
car.SpeedLimitExceeded += new SpeedLimitExceededEventHandler(CarSpeedLimitExceeded);

The first line of code above creates a new Car object. The second line using the compound assignment notation to link the CarSpeedExceeded method to the SpeedLimitExceeded event of the object. Now when the event is fired, the linked method will be executed.

To test the event, modify the Main method as follows and execute the program:

static void Main(string[] args)
    Car car = new Car();
    car.SpeedLimitExceeded +=
        new SpeedLimitExceededEventHandler(CarSpeedLimitExceeded);

    for (int i = 0; i < 3; i++)
        Console.WriteLine("Speed: {0}mph", car.Speed);


Speed: 30mph
Speed: 60mph
Speed limit exceeded (90mph)
Speed: 90mph


Removing Event Subscriptions

As with delegates it is important to release event references when they are no longer required. To end a subscription use the subtraction compound operator (-=). For example, to unsubscribe and release the CarSpeedLimitExceeded reference, you can use the following code:

car.SpeedLimitExceeded -= new SpeedLimitExceededEventHandler(CarSpeedLimitExceeded);

Event Arguments

Earlier in this article I mentioned the use of event arguments. These contain additional information that is passed when an event is raised. So far, we have been using a basic EventArgs object to represent these event arguments. The EventArgs class contains no properties that make it useful in itself. To provide the additional information we need to create a new class derived from EventArgs with the additional properties that we wish to pass.

3 February 2008