.NET generics: how to resolve type T in run-time?

Viewed 4700

Let me explain you in the following example what problem I'm solving:

class Animal {}
class Cat: Animal {}
class Dog : Animal { }

interface IAnimalHandler<in T> where T: Animal
{
    void Handle(T animal);
}

class AnimalHandler : 
    IAnimalHandler<Cat>,
    IAnimalHandler<Dog>
{
    public void Handle(Cat animal)
    {
        Console.Write("it's a cat !");
    }

    public void Handle(Dog animal)
    {
        Console.Write("it's a dog !");
    }
}

So now I want go through all animals and run appropriate handler like this:

  var ah = new AnimalHandler();
  var animals = new List<Animal> { new Cat(), new Dog() };
  animals.ForEach(a => ah.Handle(a));

However this code would not work (Can not resolve method Hanler<>...) just because .NET compiler needs to know before compilation which type is used here, so what might be the best solution for this issue? In other words, I need to ask .NET compiler to take appropriate handler of type T for every instance of type T in run-time. I do not want to use multiple if statements checking instance type.

UPDATE: Sorry for missing it, it seemed obvious to me, but now I understand it's not so obvious: AnimalHandler class contains logic not supposed to be part of domain objects Cat and Dog. Think about them as pure plain domain objects, I do not want them to know about any sort of handlers

7 Answers
Related