Why return IEnumberable<float> instead List<float>?

What is the purpose of using IEnumberable of floats rather than list of floats? I know that you need to yield return but what is the benefit of that over a List return type?

I don’t see the user case you’re specifically talking about, but not every collection needs the overhead that comes with a list. If that’s the case an IEnumerable is enough.

Oh sorry I shouldve provided context, in the IModifierProvider, IEnumerable return type was used instead of List and was just wondering why that is the case?

A list is a subtype of IEnumerable. If we make it a list, we can only return a list (and its subtypes), but if it is IEnumerable we can return all subtypes of IEnumerable, like arrays, too. And like @MichaelP said, sometimes we don’t need the overhead that comes with a list.

And in this case, we really really don’t need the overhead of a list… Either with a List<float> or an IEnumerable<float>, we have to iterate over the values and add them up. With a list, all of these values have to be copied into a class, which goes on the heap and will eventually need to be garbage collected. With the IEnumerable, we just have to pass the floats back. With a List, if there are no values to return, we still have to return an empty list (again, that goes on the heap to get garbage collected later). With an IEnumerable, if there are no values, the foreach loop is simply told there is no Next().

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms