IEnumerable & Good Practices (& WCF)
Is it a good practice to use IEnumerable
application-wide whenever you don't need to actually add or remove th开发者_如何学运维ings 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..
I don't like to return or accept IList<T>
or List<T>
because they implies the ability to modify a collection.
So prefer to return T[]
as fixed-sized collection. Also array can be easily mapped to any other framework, platform, etc.
And prefer to accept IEnumerable<T>
to emphasize that a method will enumerate that collection.
精彩评论