Celdor
Celdor

Reputation: 2597

IList<> returned type instead of List<>

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

Answers (3)

Ali Kazmi
Ali Kazmi

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

Lasse V. Karlsen
Lasse V. Karlsen

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.

  • Input parameters should be as open and general as possible. Don't take an array if you can use any collection type that can be enumerated over. (ie. prefer IEnumerable<int> over List<int> if all you're going to do is do a foreach)
  • Output parameters and return types should be as specific as possible, but try to return the most usable and flexible data type possible without sacrificing performance or security. Don't return a collection that can only be enumerated over (like 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:

  • Enumerated over (streaming access)
  • Accessed by index (random access)
  • Modified (Add, Delete, etc.)

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

Alan Tsai
Alan Tsai

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

Related Questions