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.

pondermatic
  • 6,453
  • 10
  • 48
  • 63

2 Answers2

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.

Bakudan
  • 19,134
  • 9
  • 53
  • 73
Matt Hamilton
  • 200,371
  • 61
  • 386
  • 320
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).

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