Many times while writing functions that accept enumerable types I face this confusion. Which API exposed will be better from the following options:
public void Resolve(Func<bool>[] howtos)
public void Resolve(IEnumerable<Func<bool>> howtos)
public void Resolve(List<Func<bool>> howtos)
I usually decide based on the following:
if the input needs to be modified by adding or deleting items then use List<T>
else use IEnumerable<T>
. Not sure about Array
option.
Are there other points that need to be considered while deciding on the API to be exposed? Are there any rule of thumb that clearly identified situations in which on should be preferred over the other?
You should always accept the least restrictive parameter types.
That means IEnumerable<T>
, ICollection<T>
, or IList<T>
.
This way, the client is free to pass any kind of implementation, such as an array, HashSet<T>
, or ReadOnlyCollection<T>
.
Specifically, you should take an IEnumerable<T>
if you only need to iterate the data, ICollection<T>
if you also want to add or remove items, or if you need to know the size, and IList<T>
if you need random access (the indexer).