views:

961

answers:

6

I've read a couple of blog posts mentioning that for public APIs we should always return ICollection (or IEnumerable) instead of List. What is the real advantage of returning ICollection instead of a List?

Thanks!

A: 

An enumerator only returns one entity at a time as you iterate over it. This is because it uses a yield return. A collection, on the other hand, returns the entire list, requiring that the list be stored completely in memory.

The short answer is that enumerators are lighter and more efficient.

Soviut
Huh?! I think he means how to set the return type, not the actual object to return. It's a matter of class interface contract.
Mehrdad Afshari
He was asking what the advantage to returning an enumerator versus a list was, not how to.
Soviut
A: 

ICollection is just an interface, while List is a specific implementation of that interface. What if you wanted to later on use some other container besides a list? If you publicly expose an ICollection interface, you can change your internal container to something else later on - as long as the new container also implements the ICollection interface.

ccoxtn
+1  A: 

It gives you more freedom when choosing the Underlying data structure.

A List assumes that the implementation supports indexing, but ICollection makes no such assumption.

This means that if you discover that a Set might provide better performance since ordering is irrelevant, then you're free to change your approach without affecting clients.

It's basic encapsulation.

Allain Lalonde
A: 

I would think IList would be more appropriate, but...

R. Bemrose