IList vs IEnumerable for Collections on Entities
Asked Answered
S

2

150

When I have entities in my domain with lists of things, should they be exposed as ILists or IEnumerables? E.g. Order has a bunch of OrderLines.

Superhighway answered 18/12, 2008 at 2:17 Comment(2)
Would it be wise to implement both?Stretto
It would not. An IList inherits from IEnumerable.Achromatic
P
186

IEnumerable<T> represents a series of items that you can iterate over (using foreach, for example), whereas IList<T> is a collection that you can add to or remove from.

Typically you'll want to be able to modify an Order by adding or removing OrderLines to it, so you probably want Order.Lines to be an IList<OrderLine>.

Having said that, there are some framework design decisions you should make. For example, should it be possible to add the same instance of OrderLine to two different orders? Probably not. So given that you'll want to be able to validate whether an OrderLine should be added to the order, you may indeed want to surface the Lines property as only an IEnumerable<OrderLine>, and provide Add(OrderLine) and Remove(OrderLine) methods which can handle that validation.

Popovich answered 18/12, 2008 at 2:27 Comment(2)
You can also use a IReadOnlyList or IReadOnlyCollection if you need the list materialized but you don't want to add or remove from it.Belloir
Then IReadOnlyList makes no sense.Esteresterase
S
25

Most of the time I end up going with IList over IEnumerable because IEnumerable doesn't have the Count method and you can't access the collection through an index (although if you are using LINQ you can get around this with extension methods).

Simonette answered 14/9, 2009 at 4:19 Comment(3)
I believe you can always instantiate an IList implementation with the IEnumerable if you need to access the count method and the like for example: IEnumerable<string> enumerable = <some-IEnumerable> List<string> myList = new List<string>(enumerable); However, how you expose your collection should depend on considerations such as whether you want the collection property to be immutable (IEnumerable would't allow you to modify the collection) or not (read IList)Vary
IEnumerable<T>.Count() checks to see if the underlying type is an ICollection<T> which does implement a Count property.Locution
"you can't access the collection through an index" - what about ElementAt method?Coquette

© 2022 - 2024 — McMap. All rights reserved.