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:
protected readonly int[] numbersArray;
public ParentSchedule() : this(new int[48])
{
}
protected ParentSchedule(int[] numbersArray)
{
this.numbersArray = numbersArray;
}
Then I have this child class:
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.
See more on this question at Stackoverflow