Is there any way to use an abstract class as a generic type? I've given a very simple example below to simulate what I need. I get an error that an implicit conversion cannot be made for variable genericBehavior.
public abstract class AnimalBase { } // Cannot edit
public class Dog : AnimalBase { } // Cannot edit
public class Cat : AnimalBase { } // Cannot edit
public interface IAnimalBehavior<T> where T : AnimalBase { }
public class CatBehavior : IAnimalBehavior<Cat> { }
public class DogBehavior : IAnimalBehavior<Dog> { }
public class Startup
{
public Startup()
{
IAnimalBehavior<Cat> catBehavior = new CatBehavior();
IAnimalBehavior<AnimalBase> genericBehavior = new CatBehavior(); // This doesn't work
}
}
Ultimately, in my .NET Core Startup, I'd like to be able to have the following:
services.AddScoped<IAnimalBehavior<AnimalBase>, CatBehavior>();
or
services.AddScoped<IAnimalBehavior, CatBehavior>();
What's the best approach?