Which interface to choose?

Which data collection interface is preferable for the system? By system, I mean repositories, services, etc. So I need to select IEnumerable, ICollection, IList, or maybe even List.

I suppose it would theoretically be better to use IEnumerable. But this is less convenient to use: for example, I should use the GetElementAt method instead of the indexer.

My current choice is IList, but I doubt this decision.

+4
source share
2 answers

In fact, it all depends on what type of access you want to allow for consumers of your repositories, services, etc.

If you only want consumers to read the collection, use IEnumerable<T> (write methods are not available).

If you want consumers to add directly to the collection, the methods in ICollection<T> will give them that.

In general, I try to expand collections as IEnumerable<T> as often as possible. When users want to add something to the collection, they should call a separate method, and not directly write to the collection. This gives you the ability to verify your entry, perform other checks, etc.

+5
source

If you want to allow indexer access, you must use IList<T> . The general rule is to use the least specific type, which still meets all usage requirements. And in your case, it looks like a list. (and, of course, IList<T> less specific than List<T> )

+5
source

All Articles