Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable & Good Practices (& WCF)

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.

like image 630
User Avatar asked Aug 29 '11 14:08

User


2 Answers

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.

like image 107
Joe Avatar answered Sep 22 '22 05:09

Joe


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..

like image 31
Peter Avatar answered Sep 22 '22 05:09

Peter