To use such great function as ConvertAll()
, I have to convert IList
to List
, it's painful.
views:
350answers:
5Because the interface defines a single behaviour, while a class can implement several different interfaces and also have features not specified by an interface.
If you want the capabilities of the List<T>
class, don't use an IList<T>
reference. Use a List<T>
reference from the start.
Why don't use IEnumerable<T>.Select
instead of List<T>.ConvertAll
? Since IList
inherits IEnumerable
. See this question on SO.
Note that List<>
is an implementation of IList<>
with actual storage, i.e. it holds an array in the background. In general, an IList<>
can be a proxy to something else. In db4o and linq to sql, your IList<>
could 'point to a query', i.e. accessing the list will trigger a database operation.
This way, you can perform myList.Skip(600).Take(20);
to perform pagination and only in this step will the actual query be executed. A List<>
containing a million entries will be huge, while there may be IList<>
s that have a huge Count
, but don't eat a significant amount of memory - as long as you don't access the elements.
ConvertAll
will require each and every object be instantiated so it is a costly operation. Thus, it is better to make the operation explicit and force you to retrieve a specific implementation of the interface. Obviously, conversion requires all objects to be instantiated anyway, so there's no benefit in doing it lazily.
The IList
interface is designed to be implemented far and wide. By omitting convenience methods, that means less work to implement the interface and less opportunity to write bugs.
Fortunately, LINQ side steps this and adds a bunch of useful methods through the "extension method" feature. Select
and Cast
are particularly useful for conversion purposes. Be sure that you target .NET Framework 3.5, reference the System.Core
assembly, and have a using System.Linq;
to see it.
Simply because IList(T)
is an interface, while List(T)
is one of several classes in the .net bcl that implements IList(T)
for the purpose of having indexer functionality. Not all classes that implement IList(T)
will require a ConvertAll()
method, which is used for converting a generic list of a certain generic type into another.