I recommend to use the new IReadOnlyList
and IReadOnlyCollection
Interfaces to expose a collection (requires .NET 4.5).
Example:
public class AddressBook
{
private readonly List contacts;
public AddressBook()
{
this.contacts = new List();
}
public IReadOnlyList Contacts { get { return contacts; } }
public void AddContact(Contact contact)
{
contacts.Add(contact);
}
public void RemoveContact(Contact contact)
{
contacts.Remove(contact);
}
}
If you need to guarantee that the collection can not be manipulated from outside then consider ReadOnlyCollection
or the new Immutable collections.
Avoid using the interface IEnumerable
to expose a collection.
This interface does not define any guarantee that multiple enumerations perform well. If the IEnumerable represents a query then every enumeration execute the query again. Developers that get an instance of IEnumerable do not know if it represents a collection or a query.
More about this topic can be read on this Wiki page.