I have a method which uses a generic parameter and requires the downcasted form of the instance. For example,
public abstract class Animal {
}
public class Dog : Animal {
}
public class Cat : Animal {
}
public class AnimalHandler {
public virtual void Pet<T>(T animal)
{
}
}
Given a collection of animals.
public List<Animal> Animals { get; set; }
How do I downcast individual animals before calling the Pet method?
I currently having working in this form.
if (animal is Dog) {
_animalHandler.Pet((Dog)animal);
}
if (animal is Cat) {
_animalHandler.Pet((Cat)animal);
}
Ideally, it would be something of this form.
var type = animal.GetType();
_animalHandler.Pet(animal.CastTo(type));
Clarification: I need the instance to be of the downcasted type before it is passed to the method. I need a Dog or Cat specifically to be passed in.
You can accomplish this using the new .NET 4
dynamickeyword:Notice the cast to
dynamicin the calls toPet. Though doing it this way negates the necessity ofPetbeing generic in the first place.