7.6. Passing Specialized Parameters to and from an Event


You have implemented Recipe 7.5, but you want to allow an event listener to be able to cancel an action that raised a particular event. For example, if a class attempts to create a new directory, you want to be able to verify that the directory is being created in the correct location. If the directory is not being created in the correct location (perhaps an insecure location), you want to be able to prevent the directory’s creation.


Use a class derived from EventArgs as the second parameter to the event handler. In this example, we use CancelEventArgs, a class defined in the .NET Framework Class Library. The Solution for Recipe 7.5 has been modified to include an event that is raised before the Create method of the DirectoryInfoNotify object actually creates a new path. An object of type CancelEventArgs is passed to this new event to allow any listeners of this event to cancel the Create method action. The modified class is shown here with the modifications highlighted:

using System;
using System.ComponentModel;
using System.IO;

public class DirectoryInfoNotify
    public DirectoryInfoNotify(string path)
        internalDirInfo = new DirectoryInfo(path);

    private DirectoryInfo internalDirInfo = null;
    public event CancelEventHandler BeforeCreate;
    public event EventHandler AfterCreate;
    public event EventHandler AfterCreateSubDir;
    public event EventHandler AfterDelete;
    public event EventHandler AfterMoveTo;

    protected ...

Get C# Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.