Reputation: 7267
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;
}
Upvotes: 6
Views: 1214
Reputation: 70718
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
.
Upvotes: 1
Reputation: 3118
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.
Upvotes: 0
Reputation: 40583
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.
Upvotes: 0
Reputation: 33139
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.
Upvotes: 1