3

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 ?

Titan
  • 181
  • 2
  • 9

5 Answers5

5

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

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • Eric Lippert's current series on Monads is also relevant (though more advanced): http://ericlippert.com/2013/02/21/monads-part-one/ – Pieter Geerkens Mar 07 '13 at 21:39
3

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
Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • I used IEnumerable once when creating a custom container and wanted to be able to "foreach" it. I dont understand what it's suposed to do here – Titan Mar 07 '13 at 23:43
  • @Titan: An "enumerable" is a sequence of items; that's why you can "foreach" it. If you want to treat a list of tigers as a sequence of animals, that's legal. If you want to treat a list of tigers as a list of animals, that's illegal because if it were legal then you could insert a turtle into the list of animals, but it is really a list of tigers. Since there is no "insert" method on `IEnumerable`, we can make it legal. – Eric Lippert Mar 08 '13 at 00:03
1

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();
Peter Karlsson
  • 1,170
  • 7
  • 15
1

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

David Hope
  • 2,216
  • 16
  • 32
1

You can use this question maybe useful for you

List<A> testme = new List<B>().OfType<A>().ToList();
Community
  • 1
  • 1