Reputation: 2597
I found this method in one of examples for dependency Injecting a Controller. What is the reason of using an interface type IList<>
instead of List<>
?
public IList<string> GetGenreNames()
{
var genres = from genre in storeDB.Genres
select genre.Name;
return genres.ToList();
}
Upvotes: 2
Views: 892
Reputation: 1458
It's somewhat basic rule in OOP. It's good to have an interface so your clients (the caller of GetGenreNames ) knows only how to call (function signature, only thing to remember, rather than implementation details etc) to get serviced.
Programming to interface supports all goodies of OOP. its more generalized, maintains separation of concerns, more reusable.
Upvotes: 0
Reputation: 391276
The actual reason, you're going to go ask the original programmer of that method that.
We can come up with a plausible reason however.
IEnumerable<int>
over List<int>
if all you're going to do is do a foreach
)IEnumerable<int>
) if you can return an array or a list you created specifically for the results (like int[]
or List<int>
).These guidelines are listed many places on the internet (in different words though) and are there to help people write good APIs.
The reason why IList<T>
is better than List<T>
is that you're returning a collection that can be:
If you were to return List<T>
you wouldn't actually add any value, except to return a concrete type instead of just any type that happens to implement that interface. As such, it is better to return the interface and not the concrete type. You don't lose any useful features on the outside and you still retain the possibility of replacing the actual object returned with something different in the future.
Upvotes: 4
Reputation: 2525
targeting interface is always better than targeting concrete type.
So if returning IList, that means anything implementing IList could be returned, give better separation.
check this out for more info
Why is it considered bad to expose List<T>?
Upvotes: 2