C# IEnumerable, ICollection, IList or List?

Viewed 2133

Can somebody explain to me why we constantly use IEnumerable all over C# when, by my logic we should be using List,IList or ICollection instead.

Look at this commit fix. enter image description here

Ok, number 1) IEnumarable should only be used for read only collections!

Great, everybody keeps repeating that (I get it), so why do I need to constantly need putting ToList() on every single database call to prevent mulit-threads creashing when the original thread disposes of context.

Surely once the query has been Enumarated to a List, we should just use List from there on to avoid confusion, thread safety issues and constantly calling ToList() on every single model, over and over.

Also on WebAPI that parse JSON, a text representation of an already enumerated object, we store it as IEnumarable again. We already know the size, we not interested in lazy loading it, we probably going to modify that object somewhere along the line, so why don't we store it as List of.

--EDIT

One important aspect about this question is that I never knew about covariance and contravariance

You cannot do List<IItem> because of runtime problems on the List implementation so you have to use IEnumarable<IItem> - This will only make sense in specific cases where you have the same entity, on two different systems, that need to work on one piece of code. Otherwise I have been using List<> since asking the question and that is probably 90% of the time correct to use in business layers. Database/Repository layers stick to IColletion now or IQueryable.

2 Answers
Related