Is it a good practice to use IEnumerable
application-wide whenever you don't need to actually add or remove things but only enumerate them?
Side question: Did you ever have any problems returning IEnumerable<T>
from a WCF service? Can that cause problems to client applications? After all, I think that will be serialized to an array.
I tend to only return IEnumerable<T>
when I want to hint to the caller that the implementation may use lazy evaluation. Otherwise, I'd usually return IList<T>
or ICollection<T>
, and implement as a ReadOnlyCollection<T>
if the result should be readonly.
Lazy evaluation can be an important consideration: if your implementation can throw an exception, this won't be thrown until the caller starts enumerating the result. By returning IList<T>
or ICollection<T>
, you're guaranteeing that any exception will be thrown at the point the method is called.
In the case of a WCF method, returning IEnumerable<T>
from a method that uses lazy evaluation means any exception might not be thrown until your response is being serialized - giving you less opportunity to handle it server-side.
I don't have any Good Practices sources, but i often tend to rely on List for my collections and it implements IEnumerable but i do pass it around as a List and not a IEnumerable, if i need it to be read only i rather pass a ReadOnlyCollection..
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