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 purposes the collection is immutable. I would think to just return an array, but some people have said to not return variable sized arrays from a function as it is “poor form”. Not sure why?
Does it matter that this needs to be .NET 2.0 compliant?
It’s bad form to return arrays if not needed, and especially to return
List<T>.Usually, you’ll want to return
IEnumerable<T>orIList<T>.If your user is going to just need to run through each element,
IEnumerable<T>will provide this capability. It also allows you to potentially implement the routine (now or later) using deferred execution.If your user needs to access elements by index, return
IList<T>. This provides all of the benefits of arrays, but gives you more flexibility in your implementation. You can implement it as an array, a list, or some other collection that implementsIList<T>, and you don’t have to convert/copy to an array.