How can I implement an easier solution, I’m looking for a better approach instead having to create a complex implementation class, appreciate some advice.
Current I’m doing the following:
public interface IAddressCollection : IList<IAddress>
{
new void Add(IAddress address);
}
so then I’ve got to implement everything something like the below the code. I want to avoid doing this, I’m looking for a simple way.
public class AddressCollection : IAddressCollection
{
private List<IAddress> _data = new List<IAddress>();
new public void Add(IAddress applicationAddress)
{
// some logic here... e.g.
if (!this.Any(x => x.AddressType != applicationAddress.AddressType))
{
_data.Add(applicationAddress);
}
}
// Plus all the members of IList
EDIT******
How can I avoid implementing all IList members, and still have a base interface which implements a collection?
Furthermore how can u get 5 votes for “What’s the question exactly?” seriously, if he gave me a half decent answer I’d give him/she a vote but not for question to a question.
The most common approach would be to derive from
Collection<T>:Collection<T>implementsIList<T>.UPDATE in response to comments.
If you want to implement custom logic when adding or removing items, it’s better to override one or more of the protected virtual methods
InsertItem,SetItem,RemoveItemandClearItems, rather than implementing a newAddmethod.InsertItemis called whenever the publicAddorInsertmethod is called to add an element to the list. SimilarlySetItemis called when an element is replaced (myCollection[index] = newValue),RemoveItemis called when the publicRemovemethod is called andClearItemswhen the publicClearmethod is called.By doing this you will address the concern raised by Florian Greinacher in the comments – your custom logic will always be executed even if the list is used polymorphically as an
IList<IAddress>orCollection<IAddress>For example, to match your sample, you could ignore inserting / setting items that don’t match a predicate with code something like the following (untested):