IEnumerable<T> as return type

Valentin Vasilyev picture Valentin Vasilyev · Dec 19, 2008 · Viewed 16.1k times · Source

Is there a problem with using IEnumerable<T> as a return type? FxCop complains about returning List<T> (it advises returning Collection<T> instead).

Well, I've always been guided by a rule "accept the least you can, but return the maximum."

From this point of view, returning IEnumerable<T> is a bad thing, but what should I do when I want to use "lazy retrieval"? Also, the yield keyword is such a goodie.

Answer

JaredPar picture JaredPar · Dec 19, 2008

This is really a two part question.

1) Is there inherently anything wrong with returning an IEnumerable<T>

No nothing at all. In fact if you are using C# iterators this is the expected behavior. Converting it to a List<T> or another collection class pre-emptively is not a good idea. Doing so is making an assumption on the usage pattern by your caller. I find it's not a good idea to assume anything about the caller. They may have good reasons why they want an IEnumerable<T>. Perhaps they want to convert it to a completely different collection hierarchy (in which case a conversion to List is wasted).

2) Are there any circumstances where it may be preferable to return something other than IEnumerable<T>?

Yes. While it's not a great idea to assume much about your callers, it's perfectly okay to make decisions based on your own behavior. Imagine a scenario where you had a multi-threaded object which was queueing up requests into an object that was constantly being updated. In this case returning a raw IEnumerable<T> is irresponsible. As soon as the collection is modified the enumerable is invalidated and will cause an execption to occur. Instead you could take a snapshot of the structure and return that value. Say in a List<T> form. In this case I would just return the object as the direct structure (or interface).

This is certainly the rarer case though.