1
Answer

Runtime Child Object Creation

James

James

16y
1.8k
1

Hello all,

Perhaps this question comes up a lot, but I'm having trouble finding a solution to my problem. This is mostly because I'm not exactly sure what to look for (and there's lots of information about casting etc. at runtime). My issue is the following (simplified):

I have a class Animal, and two derived classes Dog and Cat, each with their own various methods and variables etc, which are distinct form the parent class.

public class Animal {
// Animal methods etc.
}

public class Dog:Animal {
// Dog methods etc.
}

public class Cat:Animal {
// Dog methods etc.
}

So far so good, but my issue is that in my program, I only need to have a single instance of the Animal class, but there is no way of knowing (until run-time), whether it will be a Dog or a Cat. I have the following:

Animal My_Animal();

if (ComboBox1.SelectedItem == 1)
{
My_Animal = new Dog();
My_Animal.SpecificDogMethod(); //This line fails to compile
}
else
{
My_Animal = new Cat();
My_Animal.SpecificCatMethod(); //This line fails to compile
}

I can see why it fails to compile (the complier doesn't know it will be a specific child), but ho do I solve the problem? I think I've coded myself into a bit of a corner, and I've only just started learning C#.

Thanks in advance.


Answers (1)