Reputation: 191
I work in C# here, let's say i have:
class A
{}
class B : A
{}
List<B> myList;
I would like, in a part of the code cast this myList as List< A>,
but when I try to, I get an error:
List<A> myUpcastedList = (List<A>)myList; //not working
is it possible to do it ? if yes, what is the syntax ?
Upvotes: 3
Views: 842
Reputation: 660289
A list of tigers cannot be used as a list of animals, because you can put a turtle into a list of animals but not into a list of tigers.
In C# 4 and 5 this is legal if you use IEnumerable<T>
instead of List<T>
because there is no way to put a turtle into a sequence of animals. So you can say:
List<B> myList = new List<B>();
IEnumerable<A> myUpcastedList = myList; // legal
Upvotes: 3
Reputation: 125640
List<B>
cannot be casted to List<A>
. You have to create new List<A>
and fill it with items from source commection. You can use LINQ to Objects for that:
var aList= bList.Cast<A>().ToList();
You should also read a bit about covariance and contravariance, e.g. on Eric Lippert’s Blog
Upvotes: 5
Reputation:
You can use this question maybe useful for you
List<A> testme = new List<B>().OfType<A>().ToList();
Upvotes: 1
Reputation: 2256
I was able to:
List<A> myUpcastedList = myList.ToList<A>();
this makes a copy of the list though... not sure that's what you intended
Upvotes: 1
Reputation: 1180
As far as I'm aware this is not possible. An alternative would be to do the following.
using System.Linq;
var myUpcastedList = myList.Cast<A>().ToList();
Upvotes: 1