Search code examples
c#.netvb.netdesign-principles

Should I favour IEnumerable<T> or Arrays?


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)?


Solution

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