Sorry for the vague title -- I'm not exactly sure how to succinctly say what I want to do. I'll use an example to illustrate what I'm working with:
Let's say I have an Animal
base class. Then I have a few classes that derive from Animal
: Bear
, Cat
, and Dog
. Then, I have a generic repository that's defined as so:
public class AnimalRepository<TAnimal> where TAnimal : Animal, new()
{
// Some stuff
}
Now, in some other method of some other class, I need to initialize an AnimalRepository
object, but the type depends on which Animal I have. If I have a Bear
, then I want:
AnimalRepository<Bear> bearRepository = new AnimalRepository<Bear>(unitOfWork);
etc. for each animal.
My initial hope was that I could just do something like this:
Type animalType; // this is either a Bear or Cat or Dog
AnimalRepository<animalType> animalRepository = new AnimalRepository<animalType>(unitOfWork);
This is of course not possible, since that's not valid C# code. The gist of what I want to do there would require reflection, and I don't think I want to get into that.
Then I thought I could just write a switch statement like so:
string animalType;
var animalRepository;
switch (animalType)
{
case "Bear":
animalRepository = new AnimalRepository<Bear>(unitOfWork);
break;
case "Cat":
animalRepository = new AnimalRepository<Cat>(unitOfWork);
break;
case "Dog":
animalRepository = new AnimalRepository<Dog>(unitOfWork);
break;
default:
break;
}
This isn't valid either, though, because you can't just have var AnimalRepository
(it says "Implicitly-typed variables must be initialized"). So then I thought I could do this:
string animalType;
AnimalRepository<Animal> animalRepository;
switch (animalType)
{
case "Bear":
animalRepository = new AnimalRepository<Bear>(unitOfWork);
break;
case "Cat":
animalRepository = new AnimalRepository<Cat>(unitOfWork);
break;
case "Dog":
animalRepository = new AnimalRepository<Dog>(unitOfWork);
break;
default:
break;
}
But now it says:
"Cannot implicitly convert type AnimalRepository<Bear>
to AnimalRepository<Animal>
."
I thought this would be allowed since Bear
derives from Animal
. I'm guessing it doesn't work like this? Is there a cast I can do? Or a different solution to what I'm trying to do? I know I could just initialize the repositories inside each case of the switch statement and do all the work with each repository in each case, but I'd prefer to have the switch statement just initialize the repository, then do the work with it after. That way I don't have to repeat a bunch of code for each animal.