Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the real advantage of returning ICollection<T> instead of a List<T>? [duplicate]

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)?

like image 257
Martin Avatar asked Jan 08 '09 21:01

Martin


People also ask

Is it better to return IEnumerable or list?

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>.

What is the difference between ICollection and list?

ICollection<T> is an interface, List<T> is a class.

Should I use IList or ICollection?

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> ).

Why is ICollection used?

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.


3 Answers

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.

like image 103
Soviut Avatar answered Oct 16 '22 08:10

Soviut


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.

like image 29
Allain Lalonde Avatar answered Oct 16 '22 10:10

Allain Lalonde


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

like image 1
Powerlord Avatar answered Oct 16 '22 09:10

Powerlord