I'm trying to cast an object in a generic object where I need to change the type dynamically.
Dog<T>
inherits Animal
, class "T
" must inherit from EntityBase
. For example, Chihuahua
inherits EntityBase
.
for (int i = 0; i < list.Count(); i++) {
if (list?.ElementAt(i)?.GetType().GetTypeInfo().BaseType == typeof(Animal))
{
var type = list.ElementAt(i).GetType();
// is wrong, must use a class no a type
// var animal = list.ElementAt(i) as GenericObject<Dog<type>>
// Correct syntax but cast results null
var animal = list.ElementAt(i) as GenericObject<Dog<EntityBase>>
// animal is null
DoStuff(animal);
}
If I use this code, it works:
if (list?.ElementAt(i)?.GetType() == typeof(Dog<Chihuahua>))
{
DoStuff(list.ElementAt(i) as Dog<Chihuahua>);
}
I want to do this as generically as possible, thanks a lot!
I will share the project I'm doing when I finish!