Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What collection interface to choose?

Tags:

c#

.net

What collection interface is preferred for the system? By system I mean Repositories, Services, etc. So I need to choose IEnumerable, ICollection, IList or may be even List.

I guess theoretically it would be better to use IEnumerable. But it is less convenient to use: for example, I have to use GetElementAt method instead of indexer.

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

like image 927
SiberianGuy Avatar asked Dec 27 '22 16:12

SiberianGuy


2 Answers

It really comes down to what type of access you want to allow for consumers of your Repositories, Services, etc.

If you only intend consumers to read through the collection, use IEnumerable<T> (no write-type methods are available).

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

In general, I try to expose collections as IEnumerable<T> as often as I can. When users want to add something to the collection, they have to call a separate method rather than directly writing to the collection itself. It gives you a chance to validate the input, perform other checks, etc.

like image 190
Eric Olsson Avatar answered Dec 30 '22 09:12

Eric Olsson


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

like image 35
Kirk Woll Avatar answered Dec 30 '22 10:12

Kirk Woll