What should I use as return type of method IEnumerable, IList, Collection or what

1.2k Views Asked by At

I am making a library which is going to be used widely by different applications. You can say that it is sort of a public library or SDK.

Currently I am working on a function which takes a list of Points performs some calculation on these points and then return list of updated points. So my question here is what should I use as return type and in my parameters. IList, IEnumerable or Collection.

So here it the function. I am unaware what user will do with the output. How user uses it, is on him. So what should be best option to use here.

public static IEnumerable<Point2D> PeformSomeCalculation(IEnumerable<Point2D> points)
{
    // Do something,
    return updatedPoints;
}
4

There are 4 best solutions below

0
On

The IList<T> interface inherits from ICollection<T>, IEnumerable<T> and IEnumerable.

So if you return an IList<T>, clients that want an ICollection<T>, an IEnumerable<T> or just an IEnumerable will all be happy.

0
On

Do you want the points collection to be manipulated?

If so use ICollection or an IList as these expose Add, Clear and Remove methods.

If you need the list to be indexed then you should choose IList - this interface inherits from ICollection and IEnumerable so this may be what you are after.

If you do not require the collection to be modified or indexed then use IEnumerable.

0
On

As a parameter you should use the most specific required type. It's mean if you need in function only functionality of IEnumarable you should use IEnumarable, not ICollection or IList.

And as a return type you should use the most general type, but you should be aware for ICollection and IList type. If you use this in Linq to SQL - this function has method contains but Linq cannot translate this function in this type to SQL.

0
On

Generally I would try not to build assumptions into what the user will do, unless I am trying to enforce a rule such as this collection is read only, so I would use the most general type. Also you may consider implementing an iterator, as you are accepting a list and returning an updated list.

Making use of the yield return statement may be convenient for your clients allowing them ForEach functionality. Simple to implement.