Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a generic List<T> to a List?

Tags:

c#

generics

How can I convert a generic List to a List?

I am using a ListCollectionView and I need to provide it with an IList not an IList<T>.

I see plenty of examples to convert an IList to a IList<T>, but not the other way.

Do I just convert it manually (new List().AddRange(IList<T>)?

like image 475
kevindaub Avatar asked May 11 '11 14:05

kevindaub


2 Answers

To clarify the other answers:

IList<T> does not require an implementing type to also implement IList. IEnumerable<T> does require IEnumerable. We can get away with that with IEnumerable<T> because a sequence of T can always be treated as a sequence of objects. But a list of giraffes cannot be treated as a list of objects; you can add a tiger to a list of objects.

However, List<T> does unsafely implement IList. If you try to add a tiger to a List<Giraffe> by first casting it to IList, you'll get an exception.

So to answer the question: If all you have in hand is an IList<T>, you can speculatively cast it to IList with the "as" operator, and if that fails, then create a new ArrayList or List<object> and copy the contents in. If what you have in hand is a List<T> then you already have something that implements IList directly.

like image 67
Eric Lippert Avatar answered Oct 18 '22 01:10

Eric Lippert


As List<T> implements the IList interface, you can simply provide the List<T>. If needed, just cast it:

List<int> list = new List<int>();
IList ilist = (IList)list;
like image 26
Femaref Avatar answered Oct 18 '22 01:10

Femaref