Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I return IList<T> over List<T>? [duplicate]

Possible Duplicate:
C# - List<T> or IList<T>

It's written all over SO that you should return IList<T> from your methods and not List<T> but I can't find any really good reasons why. I keep finding code that does this, and then the calling code usually does one of two things:

  1. Call new List<T>(returnedIList) so it can use all the nice methods on List
  2. Casts back to List<T> so it can use all the nice methods on List

The first one is clunky and the second one would throw (runtime) InvalidCastException if the implementation actually changed to something else anyway (which makes it totally stupid).

If I use List<T> and for some reason have to replace it with an implementation of IList<T> that I can't inherit from List<T> then I'll get build errors and have to change some code. That's probably very unlikely and if it happens, it's not a lot of work to fix. Surely it's not worth losing the benefits of List<T> and/or having to cast/new List<T> (Exists, Find, etc.) to get them back for this unlikely scenario?

So, are there other reasons are there for returning IList<T>?

like image 826
Danny Tuppeny Avatar asked Feb 24 '11 17:02

Danny Tuppeny


2 Answers

It sounds to me like you're looking at some poor quality code.

Returning IList<T> rather than List<T> allows your code to be more flexible. You can replace the implementation with any collection that implements IList<T> without breaking any calling code. That's a good thing...but only when the functionality defined in IList<T> matches your needs.

You can generalize that to say that you should always return the most generic type possible. In most cases, you can get away with IEnumerable<T> but if you need more functionality, then IList<T> works. If that doesn't cut it, return the concrete type and be done with it.

In both of the situations you mention, there is a need to use something not directly provided by IList<T> (and if there's not, then both of those methods are in error). In those cases, either the method should return List<T> to provide the functionality needed or the caller should be using another method.

like image 141
Justin Niessner Avatar answered Sep 18 '22 14:09

Justin Niessner


The reason is so that your method can be used with anything that implements IList<T>, and not just a List. It gets even worse, though, since the advent of Linq, I've started making a lot of stuff return Enumerable<T> or even just IEnumerable!

I am not sure I understand the difficulty, though. If something is returning an actual list, and its return depends on that, or its use is specific to that, then it should return List<T>. If not, then you should have no need to cast it to a List.

like image 25
Jamie Treworgy Avatar answered Sep 19 '22 14:09

Jamie Treworgy