Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 390
fhnaseer Avatar asked Sep 12 '13 07:09

fhnaseer


People also ask

Should I return IEnumerable or IList?

You want to aim for the least possible coupling, so return an IEnumerable<T> if that is enough. It probably will be. Return an IList<T> if the situation requires that the caller gets a List that it can use to Add/Insert/Remove.

Should a method return List or IList?

Generally best practice is to accept parameters of the most generic type and to return the most specific. However, conventionally programmers tend to not want to tie themselves to the List implementation and normally return the IList interface.

Should I use IEnumerable or IList?

You use IEnumerable when you want to loop through the items in a collection. IList is when you want to add, remove, and access the list contents out of order. Save this answer.

What is the return type of IEnumerable?

IEnumerable is the return type from an iterator.


2 Answers

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.

like image 190
Roy Dictus Avatar answered Oct 17 '22 01:10

Roy Dictus


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.

like image 41
Darren Avatar answered Oct 17 '22 02:10

Darren