I'm currently working on a codebase and struggling to find an optimal and clean solution. I've removed the context of the problem to help simplify it to its root components. The Scale
property is a simplification for a more complex state of the class in the actual codebase. I have an idea (which I'll reference at the bottom) for how I could solve this issue - however the solution feels messy and just avoids the area I want to better understand.
Class Hierarchy
public class GreatGrandparent
{
public virtual int Scale { get; set; } = 1;
public virtual int GetTrueScale()
{
return Scale;
}
}
public class Grandparent : GreatGrandparent
{
public override int Scale { get; set; } = 2;
public override int GetTrueScale()
{
return Scale * base.GetTrueScale();
}
}
public class Parent : Grandparent
{
public override int Scale { get; set; } = 8;
}
public class Child : Parent
{
public override int Scale { get; set; } = 4;
}
Somewhere else in code:
public class Main
{
Child aChild = new Child();
int aChildTrueScale = aChild.GetTrueScale();
}
- Expected Result:
4
(4×1) (Refer to Edit 1) - Actual Result:
16
(4×4) - Desired Result:
64
(4×8×2×1)
I want a child to find its relative scale by taking in all factors of scale from its parents, so that would like:
child relative scale = child scale × parent scale × … × base class scale
How can I (if possible) define the GetTrueScale
method once in the parent class to get the desired result - which all children inherit - to avoid continuously overriding the method with duplicate implementations (the exception being the GreatGrandparent).
"Messy" Solution
Define a separate property/field in each class, and continuously override the aChildTrueScale()
method with a return of ClassScale * base.GetTrueScale()
where the ClassScale
is a different property on each Class.
Edit 1
The expected result was my initial expectation based on my understanding at the time - thinking that within a base
call the Scale reference would respect the change in scope change value to match that of the base
class. With some further testing it appears that regardless of what scope when a base method is called, the referenced Scale
value is always from the initial objects scope (hence 4*4).
Is it possible to refer to properties based on their scope? So in a base.GetTrueScale()
call, any references within that function call will be on the base
scope. Or am I completely missing something/trying to over simplify children?
Footnote
I've got a a bit of experience with procedural programming around data science, however I'm fairly inexperienced with object-oriented programming so forgive me if I'm ignorant to some core concepts. I’m happy to help clarify anything, thanks for taking the time to look over my first question! ^-^
(If anyone can think of a better title please let me know and I'll fix it up - was struggling to define the issue simply)