Usually my methods are as the following:
public List<int> Method1(int input) { var output = new List<int>(); //add some items to output return output; }
But FxCop advises another IList implementation instead of List, but I can’t remember which. The alternatives include returning it as an IList, ICollection or IEnumerable for more flexibility or a whole different way as the code below.:
public int[] Method2(int input) { var output = new List<int>(); //add some items to output return output.ToArray(); }
Of all alternatives, all provided and all possibilities, which is considered the best practice?
‘Framework Design Guidelines’ (2nd ed) in §8.3.1 has quite a lot to say about collections as return values, summary:
Collection<T>or a subclass ofCollection<T>for properties or return values representing read/write collections.ReadOnlyCollection<T>, a subclass ofReadOnlyCollection<T>, or in rare casesIEnumerable<T>for properties or return values representing read-only collections.(and more, but these three capture the core).
The first of those above: don’t return reference to internal collection unless you want the user to be able to change it (and then likely you should have a custom type so you have a degree of control).
I would return
IList<T>and ensure I do not define the actual type I am returning, unless I was returning an iterator (when I would useIEnumerable<T>).