views:

81

answers:

2

Hello,

I'm hoping the answer is as simple as the question, but I need to write an event for a class that implements a SortedList.

Is there a way I can create an event handler for anytime this list changes (Add, Modify, Remove)? The Add() methods and such are not override-able.

Thanks!

+2  A: 

No there is not. The best way to get this kind of behavior is to create a new class which wraps a SortedList<T>, exposes a similar set of methods and has corresponding events for the methods you care about.

public class MySortedList<T> : IList<T> {
  private SortedList<T> _list = new SortedList<T>();
  public event EventHandler Added;
  public void Add(T value) {
    _list.Add(value);
    if ( null != Added ) {
      Added(this, EventArgs.Empty);
    }
  }
  // IList<T> implementation omitted
}
JaredPar
Probably better to use the existing interfaces, ie: INotifyCollectionChanged
Reed Copsey
@Reed, Agreed depending on the scenario. But if the OP wants events for modification then yeah INotifyCollectionChanged is probably another on ethat should be implemented.
JaredPar
A: 

Instead of inheriting from SortedList, you should encapsulate it. Make your class implement the same interfaces, in addition to INotifyCollectionChanged:

public class MySortedList<TKey, TValue> : IDictionary<TKey, TValue>, 
    ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, 
    IDictionary, ICollection, IEnumerable, INotifyCollectionChanged
{
    private SortedList<TKey, TValue> internalList = new SortedList<TKey, TValue>();

    public void Add(TKey key, TValue value)
    {
        this.internalList.Add(key,value);
        // Do your change tracking
    }
    // ... implement other methods, just passing to internalList, plus adding your logic
}
Reed Copsey