Custom (Derived) <T> List

Feel free to load weapons and aim, but I want to understand why you should not do this.

I created my own class, designed to replace any List instances (which I use to update the XML objects behind them):

public class ListwAddRemove<T> : List<T> { public event EventHandler<ListModifyEventArgs> OnAdd; public event EventHandler<ListModifyEventArgs> OnRemove; new public void Add(T o) { base.Add(o); if (OnAdd != null) { OnAdd(this, new ListModifyEventArgs(o)); } } new public void Remove(T o) { base.Remove(o); if (OnRemove != null) { OnRemove(this, new ListModifyEventArgs(o)); } } } 

The idea is that when I add or remove an item from this list, my related events will fire and I can automatically process the XML.

It works like a charm, so good.

But how do I handle the conversion between object.ToList () and my derived version?

Many say that you should extract from the collection ... why?

+6
source share
2 answers

You should get from Collection<T> because it is designed so that you can override InsertItem and RemoveItem to add custom behavior, like what you do (also SetItem to add custom behavior when an existing item changes).

Therefore, it can be used as IList<T> , and any insertion / deletion will automatically use the setting.

In your case, anyone adding a List<T> to an IList<T> or base class will bypass your Add / Remove custom functionality.

Collection<T> also provides a constructor to wrap an existing list. You can expose this from a derived class to wrap the list generated by Enumerable<T>.ToList() .

UPDATE

What syntax will the constructor output, please?

Very simple:

 public class ListwAddRemove<T> : Collection<T> { public ListwAddRemove<T>() { } public ListwAddRemove<T>(IList<T> list) : base(list) { } ... implementation of overrides for InsertItem, SetItem, RemoveItem ... } 

Then use it as follows:

 IList<SomeType> list = ....ToList(); ListwAddRemove<SomeType> myList = new ListwAddRemove<SomeType>(list); 
+7
source

For one,

 void DoSomeAddingToList(List<int> list) { list.Add(1); } var list = new ListwAddRemove<int>(); DoSomeAddingToList(list); 

does not trigger events. This can lead to a weird effect, especially if you're not the only one using the class.

List<T> defines a very specific behavior for Add and Remove (since this is a specific class), and users can rely on this behavior.

I think this is usually true for using the new modifier, so this language feature should be used with caution, especially in public methods.

As already mentioned, the implementation of IList<T> (using delegation / aggregation) is probably the best choice.

+2
source

All Articles