SiberianGuy
SiberianGuy

Reputation: 25312

What collection interface to choose?

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.

Upvotes: 4

Views: 200

Answers (2)

Eric Olsson
Eric Olsson

Reputation: 4913

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.

Upvotes: 5

Kirk Woll
Kirk Woll

Reputation: 77616

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>)

Upvotes: 5

Related Questions