Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ICollection<T> Vs List<T> in Entity Framework

I only watched a few webcasts before I went head first in to designing a few Entity Framework applications. I really didn't read that much documentation and I feel like I am suffering for it now.

I have been using List<T> in my classes, and it has worked great.

Now I have read some documentation and it states that I should have been using ICollection<T>. I changed to this, and it didn't even cause a model context change. Is this because both List<T> and ICollection<T> inherit IEnumerable<T>, and that is what is actually required for EF?

However, if this is the case, why doesn't the EF documentation state that it requires IEnumerable<T> instead of ICollection<T>?

In any case, are there any downsides to what I have done, or should I change it?

like image 754
wil Avatar asked Oct 05 '11 01:10

wil


People also ask

What is difference between ICollection and list?

ICollection<T> is an interface, List<T> is a class.

Should I use ICollection or list?

If we want some more functionality like Add or remove element, then it is better to go with ICollection because we cannot achieve that with IEnumerable. ICollection extends IEnumerable. It supports non-index based operations like - Add item in Collection, remove, check contained item etc.

What is ICollection used for?

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

What is the difference between list and IList in C#?

The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index.


1 Answers

Entity Framework would use ICollection<T> because it needs to support Add operations, which are not part of the IEnumerable<T> interface.

Also note that you were using ICollection<T>, you were merely exposing it as the List<T> implementation. List<T> brings along with it IList<T>, ICollection<T>, and IEnumerable<T>.

As for your change, exposing via the interface is a good choice, despite List<T> working. The interface defines the contract but not the implementation. The implementation could change. In some instances, perhaps the implementation could be a HashSet<T>, for example. (This is a mindset you could use for more than just Entity Framework, by the way. A good object-oriented practice is to program towards the interface and not the implementation. Implementations can and will change.)

like image 171
Anthony Pegram Avatar answered Sep 18 '22 21:09

Anthony Pegram