Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does IList<T> not provide all the methods that List<T> does? Which should I use?

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.

like image 823
Martin Avatar asked Mar 04 '11 13:03

Martin


People also ask

Why is it IList and not list?

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.

What is the difference between IList and list in C#?

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.

Does List implement IList?

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.

What is IList type in C#?

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.


2 Answers

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.

like image 152
Jon Skeet Avatar answered Oct 06 '22 00:10

Jon Skeet


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.

like image 44
Darin Dimitrov Avatar answered Oct 06 '22 00:10

Darin Dimitrov