I have a function which returns a variable number of elements, should I return an array or a List? The \"collection\'s\" size does not change once returned, ie for all purpo
As you've undoubtedly seen from the answers in this thread, opinions on this subject range wide.
In general, my thoughts are the following:
If I am returning a list whose size is constant and I don't want the caller to be able to modify my data (which is 99% of the time), I'll return a ReadOnlyCollection<T>
. This gives me immutability on the client side without having to double (or triple, or whatever) the memory footprint of my data in creating a new list or an array.
I hesitate to say that "you should always return IEnumerable
or IEnumerable<T>
". While this is certainly appropriate in some cases (and these cases aren't few), the lightweight nature of the IEnumerable
interface greatly limits your functionality (no index-based retrieval being the biggest), and in many cases the underlying source of data is going to be an array anyway, even if it's a List<T>
.
An additional danger of returning IEnumerable
comes from the lazy practice of simply returning the inner list in the context of that interface. Doing that exposes you to the calling method abusing this shortcut by casting it back to the more robust collection type. A good, defensive programmer won't do this.
The lowest memory footprint comes from using a ReadOnlyCollection
built from a List
. A ReadOnlyCollection
does still expose you to danger through reflection-based abuse and capturing a reference to the mutable list, but that's a bit of a fringe case.