O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

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

7.5. Adding Events to a Sealed Class

Problem

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.

Solution

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.

Tip

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 ...

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