For example I have a couple of constants that have different values in each of derived classes. I want to use these values in the methods of base class (say to initialize some non-static fields in the constructor). I could copy-paste the same code for initialization to all the constructors, but I still wondering if there is a better solution.
I know that I cannot override fields as it was discussed here. If I want to access a field from base class that was initialized in the derived one the solution is to use a property instead. But what if I want to override static/const fields (I believe I cannot create static/const properties)?
I've tried to make the example as simple as possible:
class BaseClass
{
protected int currentSteps;
}
class ChildClass1 : BaseClass
{
public const int MAX_STEPS = 5;
public ChildClass1()
{
currentSteps = MAX_STEPS;
}
}
class ChildClass2 : BaseClass
{
public const int MAX_STEPS = 10;
public ChildClass2()
{
currentSteps = MAX_STEPS;
}
}
It would be ideal for me if I could rewrite it to something like this so as to not repeat the same code, but it wouldn't work as it was mentioned earlier:
class BaseClass
{
public const int MAX_STEPS = 0;
protected int currentSteps;
public BaseClass()
{
currentSteps = MAX_STEPS;
}
}
class ChildClass1 : BaseClass
{
public const int MAX_STEPS = 5;
public ChildClass1() : base() { }
}
class ChildClass2 : BaseClass
{
public const int MAX_STEPS = 10;
public ChildClass2() : base() { }
}
Is there an another option to do this without having to copy the code of initialization to all derived constructors? ( I the real program I have a lot of derived classes and many constants )