You should derive from Collection<T>
because it's designed to allow you to override InsertItem
, and RemoveItem
to add custom behavior such as what you're doing (also SetItem
, to add custom behavior when changing an existing item).
It can therefore be used as an IList<T>
, and any insertion/removal will automatically use the customisation.
In your case, anyone who casts to IList<T>
or the base class List<T>
will bypass your custom Add/Remove functionality.
Collection<T>
also provides a constructor to wrap an existing list. You can expose this from your derived class to wrap a list generated by Enumerable<T>.ToList()
.
UPDATE
Whats the syntax to expose the constructor 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);