I’m running into issues with being able to call functions/properties that are unique to the child class. I’m wondering if there is a way to do do something similar to the following:
public class Creature
{
public int HealthPoints {get; set;}
public string Name {get; set;}
public int AttackValue {get; set;}
public Creature();
}
public class Magical : Creature
{
public int Mana {get; set;}
}
So, in this rudimentary example, I’d have a list of Creatures and would need to be able to call from that the Mana property of any given Magical creature.
The short answer:
As you have surely seen in other answers, you can access the
Manaproperty of magical creatures as follows:Going a step further:
Since we’re talking about polymorphism already, you should know that
if (x is SomeType) { .. }can be a code smell. Let’s say you indeed have aforeachloop for processing all your creatures. It might then be better to create a virtual method in the base class, and do whatever you’re doing inside theforeachloop in that virtual method. You would then override the method in yourMagicalclass and thereby get rid of theifstatement.Let’s do an example. Let’s say, all your creatures get hit and lose some energy. Normal creatures lose health points, while magical creatures lose mana:
Your original
foreachloop now becomes much simpler:I would like to recommend a very nice presentation on this very topic to you: Conditionals and Polymorphism.