Bit of a basic question I guess, but if I want an object to own another object of type either A or B, how can the application using the object access the specific attributes? E.g.
public abstract class Animal
{
private int Age;
// Get Set
}
public class Tiger: Animal
{
private int NoStripes;
// Get Set
}
public class Lion : Animal
{
private bool HasMane;
// Get Set
}
public class Zoo
{
private Animal animal;
// Get Set
}
public static void Main()
{
Zoo zoo = new Zoo();
zoo.animal = new Tiger();
// want to set Tiger.NoStripes
}
This is the gist of inheritance and polymorphism.
If you are able to determine that an instance of Animal is in fact an instance of Tiger, you can cast it:
However, if you try do do this on an instance of Animal that isn’t a Tiger, you’ll get a runtime exception.
for example:
There is an alternative casting syntax that using the “as” keyword, which returns null, instead of an exception if the cast fails. This sounds great, but in practice you’re likely to get subtle bugs later on when the null object gets consumed.
To avoid the null reference exception, you can null check of course