I have this parent class:
public class ParentSchedule
{
    protected readonly int[] numbersArray;
    public ParentSchedule()
    {
        numbersArray = new int[48];
        //code
    }
}
Then I have this child class:
public class ChildSchedule: ParentSchedule
{
    public ChildSchedule()
    {
        numbersArray = new int[24]; //compile time error here
        //code
     }
}
However, at in the child class, I have this error:
A readonly field cannot be assigned to (except in a constructor or a variable initializer)
I tried adding the keyword base:
public ChildSchedule() : base()
But I still got the same error. Is there a way for me to write to the readonly field from the child class?
Is there a way for me to write to the readonly field from the child class?
No. A readonly field can only be assigned in the constructor of the type that declares it.
Perhaps you should make a protected constructor in the base class which contains the value to assign to the variable:
public class ParentSchedule
{
    protected readonly int[] numbersArray;
    protected ParentSchedule(int[] numbersArray)
   {
        this.numbersArray = numbersArray;
    }
}
Then the child class can chain to that constructor:
public class ChildSchedule: ParentSchedule
{
    public ChildSchedule() : base(new int[24])
    {
    }
}
Note that the problem isn't accessing the variable (as per your title) - it's assigning to the variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With