tags:

views:

104

answers:

3

I'm looking at some code samples for Entity Framework 4 and the author created a method that returns ICollection<Person>. I know ICollection is an interface. I know Person is the type of object in the collection. I know I'm getting back a collection of Persons.

The question. Why ICollection? Why not List<>? Why is an interface being used like this? I've used interfaces as "blueprints" for classes, specifying the required members but I don't really understand the usage here.

+12  A: 

It's often better to return interfaces instead of concrete classes in public API.

This allows the implementation to change later. For example, it may, in fact, be returning a List<T> at the moment. However, later, an optimization could be made to return a different type of collection which may have better memory efficiency, allow streaming, or one of many other advantages. As long as that class still implements ICollection<T>, the implementation is free to switch without causing a breaking API change.

Reed Copsey
Just as IEnumerable and other such interfaces are used all over .net.
Mark
A good example is returning IEnumerable<T>, when using the `yield return`: http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx. With that combination, you don't have to populate the entire list before you return it. If the user is only interested in part of the list, only the part they read through will be populated. This also can simplify the code that generates the list, since you don't have to create a temporary list to return the result.
Merlyn Morgan-Graham
Yes - IEnumerable<T> is even more flexible than ICollection<T>, but ICollection<T> is, in turn, more flexible than IList<T>. The simpler the interface you return, the more options you have for changing the implementation later...
Reed Copsey
A: 

One of the key points of the GoF Design Patterns book is to program to an interface, not to an implementation. The reason for this is the freedom it provides. By returning an interface instead of a specific type, the implementation may more easily be changed in the future without affecting the calling code.

Brian Rasmussen
A: 

Unless your users wants it from you, your API should expose as little implementation details as possible, and in this case using List<Person> is implementation detail. For example, if you or your users know that they want to access result set by index, than maybe it better return IList<Person> instead of ICollection<Person>, but if you not sure about users scenarios you should expose the most base abstractions as you can (i.e. in this case maybe IEnumerable<Person> would be enough).

And remember, if lately you decide use more derived return type, it wouldn't break any existing clients, but you can't use more based return type without break some of them.

Sergey Teplyakov