I’m still relatively new to C#.NET so I’m sure that there is something obvious that I’m missing but here it is: I’m having trouble getting some variables out of a particular class.
The class in question looks like this:
class AridPlanet : Arid
{
public const int area = 95;
}
As you can see this class inherits from the following class:
abstract class Arid : Astro
{
public const int metal = 2;
public const int gas = 2;
public const int crystals = 0;
public const int fertility = 5;
}
Which in turn inherits from the following class:
abstract class Astro
{
public int metal;
public int gas;
public int crystals;
public int fertility;
public int area;
}
I attempt to get the variables in the following:
class Base
{
private int metal;
private int gas;
private int crystals;
private int fertility;
private int area;
private List<Structure> structures = new List<Structure>();
private int position;
private Astro selectedAstro;
public Base(Astro astro, int position)
{
this.selectedAstro = astro;
this.metal = selectedAstro.metal;
this.gas = selectedAstro.gas;
this.crystals = selectedAstro.crystals;
this.fertility = selectedAstro.fertility;
this.area = selectedAstro.area;
this.position = position;
//Code ommited
}
}
The astro parameter is passed to the Base constructor as a specific astro type, for example AridMoon.
When I run the code to see what the Base variables are assigned to I see that they are all assigned to 0. To me, this suggests that the code is trying to assign the variables from the top most superclass of AridPlanet which is Astro.
However, as I understood inheritance, the compiler should look at the class indicated first before moving on to superclasses.
Any thoughts on what is going wrong? I’m sure that it’s something simple that I’ve misunderstood.
If you reference Astro astro, you will in fact get the constants as defined in Astro. You would have to cast it to a specific subclass to get the constants defined in that subclass.
What you are probably looking for is virtual properties.
You can define
Then you can implement that abstract method in a subclass
I skipped over intermediate levels of your hierarchy, but hopefully it illustrates the point. Intermediate classes can override the abstract definition. Their subclasses can optionally supply an additional override or accept the one from the intermediate class.