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>
and List<Fruit>
are not co-variant. You'll first have to cast to List<Apple>
and then use LINQ's Cast
method to cast the elements to Fruit
:
List<Fruit> fruits = values is List<Apple> ?
(values as List<Apple>).Cast<Fruit>().ToList() :
new List<Fruit>();
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:
IEnumerable<Fruit> fruits = values as IEnumerable<Fruit>;
Or, I guess, if you need a List:
List<Fruit> fruits = (values as IEnumerable<Fruit>).ToList();
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