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.
-
Would it be wise to implement both? – PedroC88 Oct 12 '10 at 04:47
-
4It would not. An IList inherits from IEnumerable. – Unknown1987 Jun 08 '14 at 00:41
2 Answers
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.

- 19,134
- 9
- 53
- 73

- 200,371
- 61
- 386
- 320
-
5You can also use a `IReadOnlyList` or `IReadOnlyCollection` if you need the list materialized but you don't want to add or remove from it. – julealgon Jun 25 '15 at 15:20
-
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).

- 959
- 9
- 12
-
1I 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
enumerable = – Sudhanshu Mishra Dec 06 '12 at 18:28List myList = new List (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) -
11IEnumerable
.Count() checks to see if the underlying type is an ICollection – andleer Feb 26 '14 at 19:33which does implement a Count property. -
1"you can't access the collection through an index" - what about `ElementAt` method? – ivamax9 Jan 10 '17 at 09:09