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.9. Observing Additions and Modifications to a Hashtable

Problem

You have multiple objects that need to observe modifications to a Hashtable. When an item is added, deleted, or modified in the Hashtable, each of these observer objects should be able to vote to allow or disallow the action. In order for an action to be allowed to complete, all observer objects must vote to allow the action. If even one observer object votes to disallow the action, the action is prevented.

Solution

Use the HashtableObserver class to observe additions and modifications to a HashtableSubject object that is registered with this object. The HashtableSubject class is an extension of the regular Hashtable class and allows itself to be observed by the HashtableObserver class. Its source code is:

public class HashtableSubject : Hashtable { public event HashtableEventHandler BeforeAddItem; public event HashtableEventHandler AfterAddItem; public event HashtableEventHandler BeforeChangeItem; public event HashtableEventHandler AfterChangeItem; protected virtual bool OnBeforeAdd(HashtableEventArgs e) { if (BeforeAddItem != null) { BeforeAddItem(this, e); return (e.KeepChanges); } return (true); } protected virtual void OnAfterAdd(HashtableEventArgs e) { if (AfterAddItem != null) { AfterAddItem(this, e); } } protected virtual bool OnBeforeChange(HashtableEventArgs e) { if (BeforeChangeItem != null) { BeforeChangeItem(this, e); return (e.KeepChanges); } return (true); } protected virtual void OnAfterChange(HashtableEventArgs ...

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