c# – Why use ICollection and not IEnumerable or List on many-many/one-many relationships?

c# – Why use ICollection and not IEnumerable or List on many-many/one-many relationships?

Usually what you choose will depend on which methods you need access to. In general – IEnumerable<> (MSDN: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx) for a list of objects that only needs to be iterated through, ICollection<> (MSDN: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) for a list of objects that needs to be iterated through and modified, List<> for a list of objects that needs to be iterated through, modified, sorted, etc (See here for a full list: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx).

From a more specific standpoint, lazy loading comes in to play with choosing the type. By default, navigation properties in Entity Framework come with change tracking and are proxies. In order for the dynamic proxy to be created as a navigation property, the virtual type must implement ICollection.

A navigation property that represents the many end of a relationship must return a type that implements ICollection, where T is the type of the object at the other end of the relationship. –Requirements for Creating POCO ProxiesMSDN

More information on Defining and Managing RelationshipsMSDN

ICollection<T> is used because the IEnumerable<T> interface provides no way of adding items, removing items, or otherwise modifying the collection.

c# – Why use ICollection and not IEnumerable or List on many-many/one-many relationships?

Responding to your question about List<T>:

List<T> is a class; specifying an interface allows more flexibility of implementation. A better question is why not IList<T>?

To answer that question, consider what IList<T> adds to ICollection<T>: integer indexing, which means the items have some arbitrary order, and can be retrieved by reference to that order. This is probably not meaningful in most cases, since items probably need to be ordered differently in different contexts.

Leave a Reply

Your email address will not be published.