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>
)?
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.
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;
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