7.5. Adding Events to a Sealed Class


Through the use of inheritance, adding events to a nonsealed class is fairly easy. For example, inheritance is used to add events to a Hashtable object. However, adding events to a sealed class, such as System.IO.DirectoryInfo, requires a technique other than inheritance.


To add events to a sealed class, such as the DirectoryInfo class, wrap it using another class, such as the DirectoryInfoNotify class defined in the next example.


You can use the FileSystemWatcher class (see Recipe 11.23 and Recipe 11.24) to monitor the filesystem changes asynchronously due to activity outside of your program or you could use the DirectoryInfoNotify class defined here to monitor your program’s activity when using the filesystem.

using System; using System.IO; public class DirectoryInfoNotify { public DirectoryInfoNotify(string path) { internalDirInfo = new DirectoryInfo(path); } private DirectoryInfo internalDirInfo = null; public event EventHandler AfterCreate; public event EventHandler AfterCreateSubDir; public event EventHandler AfterDelete; public event EventHandler AfterMoveTo; protected virtual void OnAfterCreate( ) { if (AfterCreate != null) { AfterCreate(this, new EventArgs( )); } } protected virtual void OnAfterCreateSubDir( ) { if (AfterCreateSubDir != null) { AfterCreateSubDir(this, new EventArgs( )); } } protected virtual void OnAfterDelete( ) { if (AfterDelete != null) { AfterDelete(this, new EventArgs( )); } } protected virtual ...

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.