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)?
There's a received wisdom that it's always better to return the most specific interface – meaning the interface which has the smallest possible set of functions. By that token, since IEnumerable<T> is smaller than IList<T> you should return IEnumerable<T>.
ICollection<T> is an interface, List<T> is a class.
IList<T> is essentially an ICollection<T> with random order-based access. In this case you should decide whether or not your results require list semantics such as order based indexing (then use IList<T> ) or whether you just need to return an unordered "bag" of results (then use ICollection<T> ).
If we want some more functionality like Add or remove element, then it is better to go with ICollection because we cannot achieve that with IEnumerable. ICollection extends IEnumerable. It supports non-index based operations like - Add item in Collection, remove, check contained item etc.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With