Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is-operator on generic list

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?

like image 758
0xDEADBEEF Avatar asked Feb 19 '12 20:02

0xDEADBEEF


People also ask

Is operator in C sharp?

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.

What is generic list in C#?

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.

Is Vs as C#?

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.


1 Answers

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.

like image 59
Marc Gravell Avatar answered Sep 19 '22 19:09

Marc Gravell