I have the following class structure:
public class Fruit { }
public class Apple : Fruit { }
And then I am using a method from the .net framework that gets me a property value from a class returned as an object. So,
// values will be of type List<Apple>
object values = someObject.GetValue()
I now have this values object of type List and I want to cast it to a List of type Fruit. I tried the following but it didn’t work.
List<Fruit> fruits = values as List<Fruit>;
Anyone know how to go about casting an object to a List of its base class?
Update: At the point of casting I don’t know that the values object is of type List I just know that it should be a List of a type that inherits from Fruit.
The problem is that
List<Apple>andList<Fruit>are not co-variant. You’ll first have to cast toList<Apple>and then use LINQ’sCastmethod to cast the elements toFruit:If you don’t know the type ahead of time and you don’t need to modify the list (and you’re using C# 4.0), you could try:
Or, I guess, if you need a List: