In C# I have three classes: Person, Cat, and Dog.
Both the Cat and Dog classes have the method Eat().
I want the Person class to have a property ‘Pet’.
I want to be able to call the Eat method of both the Cat and Dog via the Person via something like Person.Pet.Eat() but I can’t because the Pet property needs to be either of type Cat or Dog.
Currently I’m getting round this with two properties in the Person class: PetDog and PetCat.
This is okay for now, but if I wanted a 100 different types of animal as pets then I don’t really want to have 100 different Pet properties in the Person class.
Is there a way round this using Interfaces or Inheritance? Is there a way I can set Pet to be of type Object but still access the properties of whichever animal class is assigned to it?
You could have the pets derive from a common base class:
And then have Cat and Dog derive from this base class:
And your Person class will have a property of type
Animal:And when you have an instance of Person:
You could also provide some common implementation for the
Eatmethod in the base class to avoid having to override it in the derived classes:Notice that
Animalis still an abstract class to prevent it from being instantiated directly.