I am working on an assignment with polymorphism and have followed online tutorials that I have found on polymorphism in c#. My first questions is am I using it correctly. I have a parent class called gameCreature and two child classes called agileCreature and predatorCreature. I put in virtual and override in the classes. When I used a loop to print out all the objects everything looked ok. Here is the code
gameCreature[] _creature = new gameCreature[sizeBig];
agileCreature[] _agile = new agileCreature[size];
predatorCreature[] _predator = new predatorCreature[size];
for (int i = 0; i < size; i++)
{
_creature[i] = new gameCreature();
}
for (int i = size; i < sizeMid; i++)
{
_creature[i] = new agileCreature();
}
for (int i = size * 2; i < sizeBig; i++)
{
_creature[i] = new predatorCreature();
}
Also, if that is correct. I am running into another problem. I am trying to call a method called consumeCreature that is only in the predatorCreature, but cannot call it. I think this is because there is no consumeCreature method in gameCreature. Besides adding a consumeCreature method to the parent, is there another way to call consumeCreature method? Here is the code for that.
_creature[_creatureNum].consumeCreature(_creature[ate]);
Can I add something to it, so it knows to use consumeCreature in predatorCreature.
If you’re sure that
_creature[_creatureNum]ispredatorCreature, you can do it in the following way:(_creature[_creatureNum] as predatorCreature).consumeCreature(_creature[ate]).Could you please provide a bit more background (namely, where do you get this
_creatureNumand why do you need the array of all creatures)?