Question

I've read a couple of blog post 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!

Duplicate: What is the difference between List (of T) and Collection(of T)?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top