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?
The is operator is used to check if the run-time type of an object is compatible with the given type or not. It returns true if the given object is of the same type otherwise, return false. It also returns false for null objects.
The Generic List<T> Class in C# is a collection class that is present in System. Collections. Generic namespace. This Generic List<T> Collection Class represents a strongly typed list of objects which can be accessed by using the index.
The is operator returns true if the given object is of the same type whereas as operator returns the object when they are compatible with the given type. The is operator returns false if the given object is not of the same type whereas as operator return null if the conversion is not possible.
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:
var vehicles = myCars as IEnumerable<IVehicle>;
if(vehicles != null) {
foreach(var vehicle in vehicles) {...}
}
Since IEnumerable<out T>
exhibits covariance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With