I have a requirement to allow or prevent modification to an ObservableCollection<T> (or at least a type that implements INotifyCollectionChanged for WPF binding) as well as the objects it contains based on a business rule.
I can solve the issue of preventing modification to contained objects, but am not sure how to approach preventing change to the collection itself. One option would be to subscribe to the CollectionChanged event and undo changes after they happen, but that is not elegant and represents a confusing contract to the client.
What other approaches are there?
You could declare your own class that implements ICollection (and friends) interfaces and have the underlying collection be a member of that class. You wouldn’t want to inherit because then someone might simply cast object reference to the base class and you’ve lost your protection.
Under normal conditions, delegate all updates to the underlying class until the collection becomes locked. When it’s locked, start throwing assertions instead of forwarding the calls below. And all read operations are always delegated.
This would essentially be a decorator pattern