We have a web project that contain its business methods in a class library project called "Bll.dll"
some methods of Bll.dll return List<> ...
from a source - that i don't remember now - told that returning Collection<> is better than returning List<>
Is it a valid ?
Note that i don't make any process on values returned from BLL methods .. just view it in a web page
views:
114answers:
5Collection<T>
is implemented, IIRC, as a wrapper around an IList<T>
, of which the default implementation is List<T>
. Therefore a Collection<T>
has at least one more abstraction than a List<T>
, but in general this won't be a bottleneck. In fact, you might consider returning IList<T>
.
Edit: here is the constructor of Collection<T>
, courtesy of reflector:
public Collection()
{
this.items = new List<T>();
}
so indeed, this wraps a layer of abstraction. The plus side of this is that you can add your own validation etc by subclassing Collection<T>
(which is not possible when using List<T>
directly or via subclassing, since there are no interesting virtual
methods).
The other thing to consider is that they will have the same overall performance in terms of "O" (assuming you use the default List<T>
implementation). Indexer lookup will be O(1)
, etc
You really should only return the interface that meets the goals you set when designing your API. For example if you only expect your clients to iterate over a collection then return IEnumerable<T>
. As to your specific question I feel ICollection<T>
is kind of useless as it lacks an indexer.
That better may not apply to the performace but only to type of the returning type.
In this case is not easy to say what is better, in my opinion that depend of the usage of method "localy" is beter to return type that we operate on.
The problem with returning a List is that the caller can modify it. If you would ever like to wire up some notification mechanism ("Notify the callee whenever the caller adds a new object to it"), you can't as a List is a dead end.
Returning a Collection/ICollection allows you to create your own implementation that has whatever you want.
Basically, a List means that you're stuck in a corner that you can't escape without a breaking change.
So Collection/ICollection/IList is preferable.
Please see this question and this article.
The best thing to do is expose a strongly typed class like CustomerCollection. That way you have a place to add properties and methods later.
Offically you shouldn't expose a List, but I personally see no problem with it.