interface IVehicle
{
void DoSth();
}
class VW : IVehicle
{
public virtual void DoSth() { ... }
}
class Golf : VW { }
class Lupo : VW
{
public override void DoSth()
{
base.DoSth();
...
}
}
in my code i have:
List<VW> myCars = new List<VW>();
myCars.Add(new Golf());
myCars.Add(new Lupo());
now i want to evaluate if i have a list of vehicles. something like:
if(myCars is List<IVehicle>)
{
foreach(IVehicle v in myCars)
v.DoSth();
}
how can i do this? the is-operator on the generic list does not work. is there another way?
Even with 4.0 variance rules, a list-of-VW is not ever a list-of-IVehicle, even if a VW is an IVehicle. That isn’t how variance works.
However, in 4.0, you could use:
Since
IEnumerable<out T>exhibits covariance.