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;
}
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.
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.
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.
IEnumerable is the return type from an iterator.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With