Keyvan Nayyeri has a blog post about exposing generic collections rather than lists in API's.
The basis of his post is that he says that it's a bad idea to expose List<T> publicly, I couldn't agree more. Actually I think it's such a bad idea that I didn't realize that it was a wide spread habit. If you're going to expose a collection it should be exposed in one of two ways in my opinion.
- The best alternative in most cases is a strongly typed collection named after what it contains (for example StudentCollection contains Student-objects), that implements at least the IEnumerable<Student> or more specific interfaces (ICollection<Student> or IList<Student>) if so needed.
- Expose the collections interface, not the implementation and don't specialize the interface more than needed. If the api just exposes a collection of students in no particular order and it should be read only expose it as an IEnumerable<Student>, not ICollection<Student> or IList<Student>.
Also when you take collections as parameters in your methods use the strongly typed collection or interfaces.
EDIT: I've found that there is actually a generic counterpart of the System.Collections.CollectionBase-class, which can be found in the namespace System.Collections.ObjectModel and it's simply called Collection<T>. This saves us the labor of having to implement our own such base class but the principles in this article still holds true.
Before generics were introduced in .net the simplest way to implement a strongly typed collection was to inherit from the System.Collections.CollectionBase-class, for some reason there is no generic version of this class so I've created one of my own (that implements bot the ICollection<T> and the ICollection interfaces). The nice thing about this abstract class is that it uses explicit interface implementation so none of the interface-methods are exposed (if the collection is not cast to the interface) this allows the developer to expose only the wanted methods through the API. The benefit of this is a much clearer API that is a lot easier to use with Intellisense since only the defined methods are shown.
For example to implement a FooCollection you'd inherit from the CollectionBase<T> class as follows:
In this way we have created a strongly typed collection that also implements both the ICollection<Foo> and the non generic ICollection interfaces we also only expose the Add-method keeping the intellisense simple and public API simple (of course all interface methods are implemented and accessible through a cast).
My implementation of CollectionBase<T> is shown below.