I'm curious if anyone has any rules-of-thumb or best practices on when it makes sense to return a deferred IEnumerable<T>
or to call ToArray()
on it before returning it from a function.
For example, as the consumer of an API I think that I would prefer for a method like IEnumerable<Widget> GetWidgets()
to throw an HttpException
when I call it and not have it throw when I'm enumerating the results.
public IEnumerable<Widget> GetWidgets(IEnumarable<int> widgetIds) {
return widgetIds.Select(id => GetWidgetFromWidgetWebService(id));
}
I always prefer returning a deferred IEnumerable<T>
when there are not significant side effects of it being deferred. If the enumerable is based on an internal collection that may likely change, for example, I would prefer to evaluate it first.
However, if the enumerable is being computed, etc, then I would typically defer it.
In case your enumerable can be practically expected to throw, eagerly evaluate it (if at all possible). You don't want the error to occur at a remote place that is unrelated to the cause of the error. You want the error right where it was caused.
After all, the method did not complete what its name advertises, so it should throw.
I usually change the return type to IList<T>
in such cases to document that it executes eagerly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With