IList vs IEnumerable for Collections on Entities

CollectionsIenumerableIlist

Collections Problem Overview


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.

Collections Solutions


Solution 1 - Collections

[IEnumerable<T>][1] represents a series of items that you can iterate over (using foreach, for example), whereas [IList<T>][2] 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.

[1]: https://msdn.microsoft.com/en-us/library/9eekhta0.aspx "MSDN documentation" [2]: https://msdn.microsoft.com/en-us/library/5y536ey6.aspx "MSDN documentation"

Solution 2 - Collections

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpondermaticView Question on Stackoverflow
Solution 1 - CollectionsMatt HamiltonView Answer on Stackoverflow
Solution 2 - CollectionsJoshSchlesingerView Answer on Stackoverflow