Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# acces property from abstract classes

I have a class structure like this:

BaseAnimal.cs:

public abstract class BaseAnimal
{
   public string? Species { get; set; }
   public double Price { get; set; }
}

Then I have this two classes:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public abstract class Carnivore : BaseAnimal
{
    public double MeatFood { get; set; }
}

public abstract class Herbivore : BaseAnimal
{
   public double GreenFood { get; set; }
}

And then I have the sub classes:

public class Ape : Herbivore
{
    public Ape()
    {
        Species = "Ape";
        GreenFood = 10.0;
        Price = 10000.0;
    }
}

Then I have a facotry which is already working with this line to get all the attributes from an animal:

public BaseAnimal[] Animals = prototypes.Values.ToArray();

And in my Main class I would like to read the properties of the Animals:

 private void cboAnimals_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
    Debug.WriteLine(animalFactory.Animals[0].);
 }

The problem with this code is, that I cannot access the properties specified in the Herbivore.cs and Carnivore.cs

>Solution :

Simplest is probably to check the type:

var foodAmount = animalFactory.Animals[0] switch {
     Carnivore c => c.MeatFood ,
    Herbivore h => h.GreenFood ,
    _ => throw new InvalidOperationException()
};

But this is a typical example of inheritance taught in introductory programming. As a general rule, if you need to check the type, you might not have thought thru your type system well enough. The idea with inheritance is that everything implementation specific should be delegated to the implementation, so the user of the object do not need to know the concrete type.

I have some difficulty providing concrete recommendations since the example is so artificial, But I would recommend reading Eric Lippert series on Wizards and Warriors for a nice introduction to inheritance, and how people often do it wrong.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading