Inheritance and container in C #

I work in C # here, let's say I have:

class A {} class B : A {} List<B> myList; 

I would like part of the code to use this myList as List< A>, <A>, but when I try, I get an error message:

 List<A> myUpcastedList = (List<A>)myList; //not working 

Can this be done? if so, what is the syntax?

+4
source share
5 answers

The tiger list cannot be used as a list of animals, because you can put the turtle on the list of animals, but not on the 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 the turtle in a sequence of animals. Therefore you can say:

 List<B> myList = new List<B>(); IEnumerable<A> myUpcastedList = myList; // legal 
+3
source

List<B> cannot be sent to List<A> . You must create a new List<A> and populate it with elements from the source. You can use LINQ for objects for this:

 var aList= bList.Cast<A>().ToList(); 

You should also read a little about covariance and contravariance, for example. on Eric Lippers Blog

+5
source

As far as I know, this is not possible. An alternative would be to do the following.

 using System.Linq; var myUpcastedList = myList.Cast<A>().ToList(); 
+1
source

I could:

 List<A> myUpcastedList = myList.ToList<A>(); 

this makes a copy of the list though ... not sure what you intended

+1
source

You can use this question, possibly useful for you.

 List<A> testme = new List<B>().OfType<A>().ToList(); 
+1
source

All Articles