I have always been taught that programming against an interface is better, so parameters on my methods I would set to IList<T>
rather than List<T>
..
But this means I have to cast to List<T>
just to use some methods, one comes to mind is Find
for example.
Why is this? Should I continue to program against interfaces, but continue to cast or revert?
I am a little bit confused why Find
(for example) isn't available on the IList<T>
which List<T>
inherits from.
List is used whenever you just want a generic list where you specify object type in it and that's it. IList on the other hand is an Interface.
The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index.
I believe List implements a version of IList because it is trivial to do, and may be useful, as you wouldn't need to wrap your list in another to pass it into another class. However it does do a type-check on any items you attempt to add and will throw if they don't match.
In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.
Personally I would use IList<T>
rather than List<T>
, but then use LINQ (Select
, Where
etc) instead of the List-specific methods.
Casting to List<T>
removes much of the point of using IList<T>
in the first place - and actually makes it more dangerous, as the implementation may be something other than List<T>
at execution time.
In the case of lists you could continue programming against interfaces and use LINQ to filter your objects. You could even work with IEnumerable<T>
which is even higher in the object hierarchy.
But more generally if the consumer of your API needs to call a specific method you probably haven't chosen the proper interface to expose.
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