1

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 )

Community
  • 1
  • 1
msgmaxim
  • 788
  • 2
  • 8
  • 15

1 Answers1

4

Adding a parameter to a protected constructor should help you achieve this:

class BaseClass
{
    public const int MAX_STEPS = 0;
    protected int currentSteps;

    public BaseClass() { currentSteps = MAX_STEPS; }
    protected BaseClass(int maxSteps)
    {
        currentSteps = maxSteps;
    }
}

class ChildClass1 : BaseClass
{
    public const int MAX_STEPS = 5;
    public ChildClass1() : base(MAX_STEPS) { }
}

class ChildClass2 : BaseClass
{
    public const int MAX_STEPS = 10;
    public ChildClass2() : base(MAX_STEPS) { }
}

It may be that you won't want the default constructor on the base class, either.

maxwellb
  • 13,366
  • 2
  • 25
  • 35
  • If you are trying to access the MAX_STEPS external to the class, you should expose a public readonly int property for MaxSteps that is set in the constructor. This way, you can get the property however it was set int the constructor, no matter which class you are referencing. – maxwellb May 11 '13 at 00:31