I am making a simulation of an ecosystem, it’s very simple so don’t worry about realism.
The reproduction method is located in the Organism class, it could be used exactly by the class Plant, except for the return type which is Organism:
public Organism Reproduce()
{
double[] copy = new double[genes.Count];
for(int i = 0; i < copy.Length; i++)
// 10% chance to mutate, change up to 10%
copy[i] = genes[i] + (Program.rand.Next(10) < 1 ?
genes[i] * 0.2 * (Program.rand.NextDouble() - 0.5) : 0.0);
return new Organism(genes);
}
I know in Ruby it’s possible to return ‘self’ so if the method is used by a class that extends this one, the method will return an object of the inheriting class.
So the question is: How can I modify this method so that when it’s called from a Plant, it will make a Plant and return one?
You will need to use generics. The simplest way would be to make just this method generic. The one issue you will come across is that you must have a public parameter-less constructor.
Then you will call this method like so.
I would go one step further and make this a separate class to make testing easier. Maybe even an extension method.
You can then call this like so.