0

I have a simple class here

class Leader : Inhabitants
{

    public int ProducedWorth { get; set; }
    public Leader(string name, int age, string profession, int producedWorth)
    {
        InhabitantID = InhabitantCount;
        Name = name;
        Age = age;
        Profession = profession;
        ProducedWorth = producedWorth;
    }
    public int GetProducedWorth()
    {
        return ProducedWorth;
    }
}

which inherits from a Inhabitant class

 class Inhabitants
{
    static protected int InhabitantCount;
    public Inhabitants()
    {
        InhabitantCount++;
    }
    public int InhabitantID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Profession { get; set; }
}

Now when I create new instances of the class it seems to work perfectly fine, but when I try to access to the producedWorth property that is only on the base class i get the error that the inherited class does not have said property?

var leadA = new Leader("Julien", 33, "Stone pit overseer", 6540)
//leadA.Name is accessible
//leadA.producedWorth is not accessible

program.cs

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Mago99
  • 53
  • 2
  • 10

3 Answers3

2

The list is a list of Inhabitants, you can only access properties of Inhabitants, the reason is that the compiler does not know that the actual object in the list is of type Leader, though you can tell him by casting to Leader:

((Leader)leadA).ProducedWorth

The line above should compile.

Dr.Haimovitz
  • 1,568
  • 12
  • 16
0

Generic lists are covariant which is why you are allowed to add Leaders to a list of Inhabitants.

Implicit conversions are allowed, you just have to not use var. Do this:

foreach(Leader ldr in leaders)
{
   // ....
}
Crowcoder
  • 11,250
  • 3
  • 36
  • 45
  • Just to make it clear, this syntax does not filter Leaders out of that list, but casts every item. So that will fail if there happens to be a plain Inhabitant there – Hans Kesting Aug 04 '18 at 14:48
  • @HansKesting yes, but the accepted answer would also fail the same way. – Crowcoder Aug 04 '18 at 14:52
-2

In the code you're executing you're creating a list of type Inhabitants which does not possess the property ProducedWorth. You need to add that property to the Inhabitants class if you want to be able to access it that way.