Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to return IEnumerable<T> [duplicate]

Should I return IEnumerable<T> from methods and properties only in cases when it is lazy evaluated?

Do you have guys any patterns when you return IEnumerable, ICollection and IList?

like image 716
Danil Avatar asked Dec 12 '22 05:12

Danil


2 Answers

I return IEnumerable whenever the caller will only need to iterate over the collection from start to finish. By using the most minimal possible interface, I ensure that the calling code is not too tightly coupled, and thus make it easier to change the code in the method or property later. If it still returns IEnumerable, nobody else has to care. If it returned List before and the new method internally represents things using, say, a HashSet, suddenly lots of other things have to change as well.

Therefore I always prefer to return collection interfaces rather than concrete collections, except in cases where the calling code really needs to know exactly what type of collection it's dealing with. I consider the operations the caller is going to need to be able to do, and find the most minimal interface which supports them.

like image 162
Matthew Walton Avatar answered Jan 01 '23 15:01

Matthew Walton


Usually if it is a list (not lazy) I return IList. Say, I do it all the time when my method is expected to return the result as a collection. I do it because it clearly states in the method signature that it is a loaded list, not lazy evaluated one, but yet using interface does not expose the concrete type (array, list, read-only list, etc).

I return IEnumerable when I do any kind of transformation on a collection that is passed in (LINQ approach)

At the same time I use IEnumerable as a parameters in my methods just to state that "this function doesn't care, it just need to be able to go through". Of course I ensure that the IEnumerable is enumerated only once within my function.

like image 28
Alexey Raga Avatar answered Jan 01 '23 16:01

Alexey Raga