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

I am creating a library that will be widely used by various applications. You can say that it is a kind of public library or SDK.

I am currently working on a function that takes a list of points, performs some calculations at these points, and then returns a list of updated points. So my question is what should I use as the return type and in my parameters. IList , IEnumerable or Collection .

So this is the function. I do not know what the user will do with the exit. How the user uses it, on him. So what should be the best option to use here.

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

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

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

+1
source

Do you want point management to be handled?

If this is used, ICollection or IList , as they expose the Add , Clear and Remove methods.

If you need a list for indexing, you should choose IList - this interface inherits from ICollection and IEnumerable so this may be what you need.

If you do not need the collection to be modified or indexed, use IEnumerable .

+1
source

As a parameter, you should use the most necessary type. This means that if you only need the function of the IEnumarable function, you should use IEnumarable, not ICollection or IList.

And you should use the most generic type as the return type, but you should know about the ICollection and IList types. If you use it in Linq for SQL - this function contains a method, but Linq cannot translate this function in this type of SQL.

0
source

In general, I would try not to speculate on what the user will do, unless I try to apply a rule, such as this collection, for reading only, so I would use the most general type. You might also consider using iterator as you accept the list and return the updated list.

Using the yield return statement can be convenient for your clients, which allows them to use ForEach functions. Ease of implementation.

0
source

Source: https://habr.com/ru/post/953684/


All Articles