February 2, 2008

IEnumerable, ICollection, IList Compared

IEnumerable<> => Allows use of 'foreach' on a collection
ICollection<> => As IEnumerable<> + Add(), Remove(), Count, Clear(), Contains(), IsReadOnly, CopyTo()
IList<> => As ICollection<> + this[int], Insert(), IndexOf(), RemoveAt(). ie. It adds indexing type list operators
    • Can use 'return yield ???' in conjunction with IEnumerable<> to only return 1 object at a time. This is where the real power of IEnumerable comes from (not from simply returning a list or an array).
    • When returning a list decide what can be exposed to the user and return the appropriate type. 
    • Maybe its best to return an ICollection<> or IList<> and if the code client only needs to enumerate the list they can cast it to an IEnumerable<>. ie. Given ICollection<Widgets> SomeMethod() … The user could invoke it as IEnumerable<Widgets> widgets = SomeMethod()

    1 comment:

    Fordy said...

    Just what I was looking for, a concise comparison. Thanks.