14

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.

User
  • 3,244
  • 8
  • 27
  • 48
  • 1
    Perhaps you should add what language you are talking about? This is not a .net-only site, after all... – Sean Patrick Floyd Aug 29 '11 at 14:43
  • 2
    While this is **not an exact duplicate**, I still suggest you have a look at this question: http://stackoverflow.com/questions/1072614/should-i-always-return-ienumerablet-instead-of-ilistt – yas4891 Aug 29 '11 at 14:51

3 Answers3

13

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.

Joe
  • 122,218
  • 32
  • 205
  • 338
1

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

Peter
  • 37,042
  • 39
  • 142
  • 198
1

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • 4
    T[] is not a read-only collection: you can modify the elements of an array. Conversely, IList does not imply the ability to modify a collection - e.g. IList.IsReadOnly is true for ReadOnlyCollection. If it's important that callers don't modify the returned collection, it's probably best to return IList and implement as a ReadOnlyCollection of immutable objects. – Joe Aug 29 '11 at 16:25