DEV Community

Discussion on: Enumerable types and interfaces, which type do you prefer to return?

Collapse
 
peledzohar profile image
Zohar Peled

Does IEnumerable really indicates anything that ICollection doesn't?
Don't forget that ICollection inherits IEnumerable...

I think that as a rule of thumb, you should return the simplest possible type that you can - while still make it usable for whomever is expected to use your method. If you know it will generally make sense to the results in a foreach loop, an IEnumerable is enough. If you want to return the count as a property, IReadOnlyCollection is a lovely option.

Please note, you don't really need to know what your users are going to do - but you should base your decision on what you allow to be done with your return value.

You should probably also read this SO post and it's answers:

I am confused about which collection type that I should return from my public API methods and properties.

The collections that I have in mind are IList, ICollection and Collection.

Is returning one of these types always preferred over the others, or does it depend on the specific…