Imagine I have a SearchService layer that has a method to search all cars starting with a certain string;
public static class Searcher{
public IAnInterface&l
I would choose IEnumerable
because it has a more central place in the framework, providing versatility for those that need it, while also providing familiarity to those who are yet to get stuck into things like LINQ.
IQueryable
would have a rather heavy requirement on it -- you couldn't, for example, return an array.
Usually for me, the choice between IEnumerable
or IList
usually ends up being whichever is easier to implement in the standard case.
Always go with IEnumerable
unless you have a serious reason not to. You can then implement the getter with yield return
.
IQueryable
is a totally different kettle of fish. Not something you'd casually implement as an alternative to a typical in-memory container.
Of the rest, there is a major different between IEnumerable
and the others: it's readonly.
Short answer: It depends.
Longer answer: Return the richest type that your client code is going to need. IList works in most cases if you don't need lazy loading. You can still use Linq to query against an IList or IEnumerable. If lazy loading is a requirement, then go with IEnumerable or IQueryable.
Side note: Returning the same interface for all services might seem like a noble goal but given different client usage patterns, you may want to return different interfaces.
If you want all your services to return the same interface then I would probably go for IEnumerable<>
.
It'll be easy enough for your callers to convert to IQueryable
or create a List
, if necessary:
IEnumerable<Car> cars = Searcher.CarsStartingWith("L");
var carsList = cars.ToList();
var queryableCars = cars.AsQueryable();
If you are using IQueryable as return type, You have a service layer with leaky abstraction.