O'Reilly logo

C# Essentials by Peter Drayton, Ben Albahari, Brad Merrill

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Events

Event handling is essentially a process by which one object can notify other objects that an event has occurred. This process is largely encapsulated by multicast delegates, which have this ability built-in.

Defining a Delegate for an Event

The .NET Framework defines many event-handling delegates for you, but you can write your own. For example:

delegate void MoveEventHandler(object source, MoveEventArgs e);

By convention, an event delegate’s first parameter denotes the source of the event, and the delegate’s second parameter derives from System. EventArgs and stores data about the event.

Storing Data for an Event with EventArgs

The EventArgs class can be derived from to include information relevant to a particular event:

public class MoveEventArgs : EventArgs {
  public int newPosition;
  public bool cancel;
  public MoveEventArgs(int newPosition) {
    this.newPosition = newPosition;
  }
}

Declaring and Firing an Event

A class or struct can declare an event by applying the event modifier to a delegate field. In this example, the Slider class has a Position property that fires a Move event whenever its Position changes:

class Slider {
  int position;
  public event MoveEventHandler Move;
  public int Position {
    get { return position; }
    set {
      if (position != value) { // if position changed
        if (Move != null) { // if invocation list not empty
          MoveEventArgs args = new MoveEventArgs(value);
          Move(this, args); // fire event
	 if (args.cancel)
            return;
        }
        position = value;
      }
    }  
  }
}

The event keyword promotes ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required