Best Type to set as return type for methods that return a collection?
I asked this on Stack Overflow:
Which is the best type to us for returning collections?
Should I use IList<T>, IEnumerable<T>, IQueryable<T>, something else? Which is best and why?
I’m trying to decide which I should use typically, both in the interface and the implementation of a few classes that I’m writing.
edit Let me nail this down a little further, I am using LINQ to SQL to return data over a WCF Service. It feels like that may make a change in the best type to use?
Mike Two answered (1 upvotes):
I default to IEnumerable. I’m shooting for the minimal interface to expose. Both
IList<T>andIQueryable<T>implementIEnumerable<T>. So unless you have other specific requirements for the methods I’d go for minimalism and use the least derived type. If you have other requirements in your calling code, such as performance of indexed lookups or getting the number of items in the collection then you might want to choose another type such asICollection<T>.
Notable comments
Nate (0 upvotes): How then would the consumer use it? if the method returns IEnumerable
Nate (0 upvotes): Per the comment above, When using ‘IEnumerable
Originally posted on Stack Overflow — 15 upvotes. Licensed under CC BY-SA.