I'm trying to cast a list of objects to its parent using generics. I have classes such as:
Entity
Node
OtherClass
Where Node/OtherClass inherits from Entity. What I want to do is something like this:
Type toType = typeof(Node); // Actually not gotten this way
Object fieldValue = field.GetValue(item);
List<Entity> entities = (List<Entity>)fieldValue;
foreach (Entity toEnt in entities)
{
// Code using toEnt using its Entity attributes...
}
I'm able to get the field using a FieldInfo reference but I'm unable to cast the list. Field value is the List of Node reference but it seems it's unable to cast it to List of Entity which should be possible since it inherits from Entity.
Casting to List of Node instead works, but I also want the code to be able to take a List of OtherClass. It also doesn't work to cast to List of objects, and then casting each individual one to Entity.
I tried using MakeGenericType, which is probably part of the solution, but I couldn't get it to work after quite a while of trying.
Thanks for your time!
A variation on the other options, but using covariance:
var sequence = (IEnumerable<Entity>) field.GetValue(item);
var entities = sequence.ToList();
This relies on the generic covariance of IEnumerable<T>, so will only work with C# 4+ and .NET 4+.
While a List<Node> isn't a List<Entity>, it is an IEnumerable<Entity>... which the above code takes advantage of.
Of course if you just need to iterate, you don't need a List<Entity>:
var sequence = (IEnumerable<Entity>) field.GetValue(item);
foreach (var entity in sequence)
{
...
}
But if you do need to create a List<Entity>, calling ToList() on an IEnumerable<Entity> should be fine.
You could do that
Linq:
List<Base> listOfBase = new List<Derived>().Cast<Base>().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