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:
new List<T>(returnedIList)
so it can use all the nice methods on ListList<T>
so it can use all the nice methods on ListThe 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>
?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With