Collection object - what interface to use

D

Doug

Hi,

I want to create a collection of objects that will be used as a
property of another object. So for example if I had a Customer object,
I would like to have an AddressCollection property within that object.
That AddressCollection property would contain one to many Addresses for
each Customer and the Address object would have properties such as
Street, City, State, etc.

I am struggling with what interface to use to do this. I've looked
into IEnumerable, IEnumerator, IList, ICollection etc but they all have
either more methods or less than what I need. I need the ability to
add to this collection and to find a certain one within it.

Any suggestions?
 
D

Doug

I'm guessing this must be a more recent version of DotNet that you are
using for that? I'm still using 1.1 (we're slow to change around
here...:)) and I don't have access to the namespace you mentioned.
 
D

Dave Sexton

Hi Doug,

Yes, I was referring to a generic collection in the 2.0 framework.

In 1.* you can use an ArrayList internally and explicitly implement IList
members that you aren't interested in using on a regular basis (but you have
to implement all members regardless):

class AddressCollection : IList
{
// explicit interface implementations aren't visible to consumers
// unless they explicitly cast AddressCollection to IList
void IList.RemoveAt(int index)
{
// implement the method anyway
list.RemoveAt(index);
}

private readonly ArrayList list = new ArrayList();

public void CopyTo(Array array, int index)
{
list.CopyTo(array, index);
}

public int Count { get { return list.Count; } }

public bool IsSynchronized { get { return list.IsSynchronized; } }

public object SyncRoot { get { return list.SyncRoot; } }

public IEnumerator GetEnumerator()
{
return list.GetEnumerator();
}

public int Add(object value)
{
return list.Add(value);
}

...
}
 
B

Brian Gideon

Doug,

At the very least you should implement ICollection. That way your
custom collection can be used every where an ICollection is used.
ICollection carries with it IEnumerable so that will give you the
ability to enumerate it. IList carries with it ICollection and adds
the ability to add, remove, and index into the collection so this might
be good to implement as well. If you need to store key-value pairs
then IDictionary would be a good candidate for implementing.

Also, take a look at CollectionBase and DictionaryBase. I find that
these base classes work most of the time when I want to create a custom
collection.

Brian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top