Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

child class constructor cannot assign to readonly variable inside

Tags:

c#

asp.net

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?

like image 233
But I'm Not A Wrapper Class Avatar asked Mar 23 '15 16:03

But I'm Not A Wrapper Class


1 Answers

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.

like image 183
Jon Skeet Avatar answered Nov 14 '22 19:11

Jon Skeet