I am making a program for a school assignment about storing a list of animals observed (I am not asking about help with the program, just something interesting I happened to stumble upon).
I wanted to make a list of animals in the animals class and thought it would be really easy and convenient to add the created animal to the list at the end of the constructor, which seemed to work out well until I ran the code.
I should have figured, but the object value is null as it is still within the constructor and (I suppose) have not in fact been created yet.
abstract class Animal
{
private static List<Animal> allAnimals;
private static int amountOfAnimals;
private int height;
private double weight;
public Animal(int height, double weight)
{
this.height = height;
this.weight = weight;
amountOfAnimals++;
allAnimals.Add(this);
}
}
//and later, when I use it in the "Program" class:
//(animalType, width and height are all user inputs)
switch (animalType)
{
case "lion":
new Lion(height, weight);
break;
case "leopard":
new Leopard(height, weight);
break;
case "cheetah":
new Cheetah(height, weight);
break;
default:
Console.WriteLine("Animal type does not exist.");
continue; //it's in a loop, so break would break that
}
I would like to know if there is any way to do what I am trying to do, even though Animal.allAnimals.Add(new Lion(height, weight))
would work. That would also require me to have a public setter on the list, unless I move it to the program class.
Just thought it was an interesting concept and would like to know if it is possible in any way, even though I highly suspect it would be considered bad practice.