Should I favour IEnumerable<T> or Arrays?

Alex Essilfie picture Alex Essilfie · Mar 1, 2011 · Viewed 15.5k times · Source

In many projects I work on, whenever I have to return a read only collection, I use the IEnumerable<T> interface and make it type specific like so:

Public ReadOnly Property GetValues() As IEnumerable(Of Integer)
    Get
        'code to return the values'
    End Get
End Property

Most of the time, I return a List but in some functions and read only properties I return an array which also serves the purpose alright by kind courtesy of Extension Methods.

My question is am I violating any design principles by returning IEnumerable<T>s instead of specific types (e.g.: List<T>, HashSet<T>, Stack<T> or Arrays)?

Answer

David picture David · Mar 1, 2011

I generally prefer IEnumerable<T> as well. The main thing is to ask yourself what actual (even minimum) functionality is being returned from the method (or passed to it, in the case of a method argument).

If all you need to do is enumerate over a result set, then IEnumerable<T> does exactly that. No more, no less. This leaves you the flexibility to return more specific types in certain cases if need be without breaking the footprint of the method.