Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IList<Type> to IList<BaseType>

I have a few classes:

class Vehicle
{
}

class Car : Vehicle
{
}

I have a list of the derived class: IList<Car> cars;

I would like to convert the list to its base class, and have tried: IList<Vehicle> baseList = cars as IList<Vehicle>;

But I always get null. Also

cars is IList<Vehicle> evaluates to be false.

Granted, I can add the items to a list if I do the following:

List<Vehicle> test = new List<Vehicle> ();

foreach ( Car car in cars )
{
   test.Add(car);
}

And I get my list, but I know there has to be a better way. Any thoughts?

like image 296
Kyle Avatar asked Sep 21 '09 22:09

Kyle


5 Answers

Use IEnumerable<T>.Cast :

IList<Vehicle> vehicles = cars.Cast<Vehicle>().ToList();

Alternatively, you may be able to avoid the conversion to List depending on how you wish to process the source car list.

like image 181
Lee Avatar answered Oct 25 '22 02:10

Lee


That sort of polymorphism that lets you cast IList<Car> to IList<Vehicle> is unsafe, because it would let you insert a Truck in your IList<Car>.

like image 45
Phil Miller Avatar answered Oct 25 '22 03:10

Phil Miller


You're facing the problem that there is limited co- and contravariance in C#. There is an interesting approach in C# 4.0, described here at the very ending. However, it creates some other limitations that are related to the truck-problem in the answer from Novelocrat.

like image 43
Marc Wittke Avatar answered Oct 25 '22 03:10

Marc Wittke


Here are a couple of approaches using Linq:

IList<Derived> list = new List<Derived>();
list.Add(new Derived());

IList<Base> otherlist = new List<Base>(from item in list select item as Base);
IList<Base> otherlist2 = new List<Base>(list.Select(item => item as Base));
like image 3
recursive Avatar answered Oct 25 '22 04:10

recursive


You can also take a look on Krzysztof's Cwalina article, Simulated Covariance for .NET Generics

like image 2
Bolek Tekielski Avatar answered Oct 25 '22 03:10

Bolek Tekielski