I'm developing an application. For argument's sake, let's say the application represents zoo(s). The data for each zoo is stored in a List <Zoo>
type variable, where Zoo
is defined as:
public class Zoo {
List<Animal> animals;
...
}
Animal
is defined as:
public abstract class Animal {
public virtual string Name {get; set;};
...
}
And various classes derive from Animal
:
public class Dog {
public int nLegs = 4;
public string furColour= "White";
public Dog() {
Name = "Dog";
}
...
}
public class Millipede {
public int nLegs = int.maxValue;
public Millipede() {
Name = "Millipede";
}
...
}
public class Goldfish {
public string colour = "Red";
public Goldfish() {
Name = "Goldfish";
}
...
}
Let's say we live in a crazy world where each Zoo
can only have one type of Animal
(but as many different instances of Animal
as they want). One particular Zoo
really likes Millipedes
:
List<Animal>.Add(new Millipede());
List<Animal>.Add(new Millipede());
List<Animal>.Add(new Millipede());
List<Animal>.Add(new Millipede());
Another Zoo
really likes Goldfish:
List<Animal>.Add(new Goldfish());
List<Animal>.Add(new Goldfish());
List<Animal>.Add(new Goldfish());
List<Animal>.Add(new Goldfish());
In theory, the Animal
class can be anything, and I have no way of knowing what different implementations will look like, but the specific Zoo
class will. Ideally, I'd like to work with List<Dog>
or List<Millipede>
, and not List<Animal>
, so I can access specific properties/methods of the Animal
subclass. I've come across Convert List<DerivedClass> to List<BaseClass>, which lists a few options and describes why casting List<Animal>
to List<Dog>
doesn't make much sense. In my particular application, this conversion could be happening for many lists with a large number of items each (1000s), multiple times per second per list, so it's not feasible for me to do a conversion each time.
For an example like the above, what is the best way to organise the class structure, so that this problem can be avoided altogether?