Reputation: 135
I have this abstract class:
abstract class Animal {
public abstract List<??????> getAnimals();
}
I want to change the return type to make this:
Animal animal;
if(/*Somthing*/){
animal = new Cat();
catList = animal.getAnimals();
}else{
animal = new Dog();
dogList = animal.getAnimals();
}
I want to return CatModelList
and a DogModelList
.
Is this possible if dog and cat would have Animal
s as base? And if not what I think is the answer, what would be the correct way of doing this?
Upvotes: 1
Views: 2012
Reputation: 156978
Then you need generics to supply the type:
abstract class Animal<T> : Animal where T : Animal
{
public abstract List<T> GetAnimals();
}
abstract class Animal
// base type to make things easier. Put in all the non-generic properties.
{ }
Where T
could be Dog
, Cat
or any other type deriving from Animal
:
class Dog : Animal<Dog>
{ }
Then you can use it using the derived class:
Dog d = new Dog();
animal = d;
dogList = d.GetAnimals();
It seems weird though. In an instance of Animal
you get the animals? I don't get that logic.
Upvotes: 5