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.
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.
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>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With