Is-operator in the general 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 there is:

 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 in the general list does not work. Is there another way?

+7
source share
3 answers

Even with the 4.0 rejection rules, a list-VW is never a list in the IVehicle category, even if VW is an IVehicle. This is not how dispersion works.

However, in 4.0 you can use:

 var vehicles = myCars as IEnumerable<IVehicle>; if(vehicles != null) { foreach(var vehicle in vehicles) {...} } 

Since IEnumerable<out T> demonstrates covariance.

+11
source

In .net 4, you can use the general variance of a parameter. Read more about it here.

+2
source

You can do it:

 if (typeof(IVehicle).IsAssignableFrom(myCars.GetType().GetGenericArguments[0])) foreach (IVehicle v in myCars) //... 

This assumes that you know that myCars is a generic type. If you don't know this for sure, you need to do an extra check first or two.

However, since you are not using any list member other than GetEnumerator, you can do this:

 if (myCars is IEnumerable<IVehicle>) //... 
0
source

All Articles