I'm just having a play around with inheritance and a few other concepts at the moment.
I have created a console app that amongst other things, holds the following classes:
Public abstract Organism
Public abstract Animal : Organism
Public Bird : Animal
Public Mammal : Animal
Public Reptile : Animal
Public Fish : Animal
Public Amphibian : Animal
Public Human : Organism
When the console app starts, I want to create a new object from either the Human, Fish, Mammal, Reptile, Bird or Amphibian class. Which one of these classes to instantiate is to be randomly chosen.
Once a class has been randomly chosen, I've used console.writeline to ask the user key questions to assign values to the given objects properties.
How do I create a random object from one of these classes?
Without using Reflection you can achieve it with a List of class Instances:
There are some "mistakes" in the code that you have to correct yourself.
If you need to choose types from a list, you could:
But for if you value simplicity/readability in your code (and you should), the following is much better if possible:
Edit: I forgot about Activator.CreateInstance (simpler than the code I suggested), but using more basic code will be more readable if there aren't very many classes, and allows more flexibility (you don't need every type to have an even probability).