none
IEnumerable<T> instead of IList<T> or Collection<T>

    Question

  • hi,
    Just wondering and see what your opinions are.

    I usually pass around the layers either a Custom Collection<T> or a Custom ListBase<T>:IList ..

    I was now wandering if instead of return from a Data Access Layer or biz layer one of those is better to actually just return an IEnumerable<T>.

    Shall I drop returning all those LIst<T> Collection<T> and use IEnumerable<T> instead?

    Would that be more flexible?

    Thanks for any suggestions






    Thanks for your help
    Tuesday, May 19, 2009 6:54 AM

Answers

All replies

  • Well, it depends.  Returning the smaller interface is usually attractive since it gives you more options to modify the implementation.  If the client has no business adding or removing items from the collection, you can enforce that somewhat by just returning IEnumerable<>.  Somewhat, the client can still cast the interface reference.  And will readily do so when you take away capabilities that the client needs.

    Hans Passant.
    Tuesday, May 19, 2009 12:30 PM
    Moderator
  • Hi devBrix,

    Complementing nobugz's answer...this article illustrate other interesting views such as performance cost of using each one.
    http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=722


    Hope you find it useful,


    Please, mark this message as answer or vote as helpful if you find it useful.
    Sergio Ortiz
    i-Card Software CTO

    View Sergio Ortiz's profile on LinkedIn View Sergio Ortiz's profile on Xing
    Tuesday, May 19, 2009 2:00 PM
  • I think returning IEnumerable is more appropriate if you need to return "read-only" data to other layers, since IEnumerable only specifies the enumeration plan over the data, no more no less.

    The benefit of passing the data with stripped down semantics like IEnumerable is that you could control how the client uses your data without causing any side effect if those side effects is not anticipated by you.

    -> Somewhat, the client can still cast the interface reference.  And will readily do so when you take away capabilities that the client needs.

    If the client does so, he or she runs the risk of implementing things depending on the implementation detail of a specific data structure, how about if the data structure is inherently unknown or complex to you as my example does .

    Hope this clears things up a little bit.

    Thanks
    Marco
    Another Paradigm Shift
    http://shevaspace.blogspot.com
    • Edited by Marco Zhou Thursday, May 21, 2009 6:59 AM bad typo
    • Marked as answer by Marco Zhou Tuesday, May 26, 2009 1:20 AM
    • Unmarked as answer by nobugzModerator Tuesday, May 26, 2009 2:11 AM
    Thursday, May 21, 2009 6:59 AM
  • Thanks a lot that helps a lot to understand it better
    Thanks for your help
    Monday, June 1, 2009 11:03 AM