简体   繁体   中英

Why can't I set this readonly property in the constructor?

I want to set the readonly porperty "EmployeeList" in the constructor, but for some reason it is not allowed, as the EmployeeList is readonly. But it works just fine for the other readonly property "Manager". The only difference being that I wrote the getter for EmployeeList myself, and for Manager it is auto-generated.

I'm not allowed to use a private setter to resolve this.

class Project
    {
        public Employee Manager { get; }

        public EmployeeList EmployeeList
        {
            //Creates a copy of the EmployeeList and returns it
            get
            {
                //...
                return listCopy;
            }
        }

        //Initializes class-variables.
        public Project(Employee manager, EmployeeList 
                        employeeList)
        {
            Manager = manager;
            EmployeeList = employeeList; //Error: EmployeeList is read-only
        }
}

Why can't I set EmployeeList and how do i fix this?

You can set a read-only automatically-implemented property in a constructor, but in your case you've specified an implementation. That compiler doesn't know what to do when you try to call a "setter" - it doesn't look through the getter and notice that you're returning the listCopy variable. (That may not even be a field - we can't see the rest of your getter code.)

So your options are:

  • Change EmployeeList to an automatically-implemented property
  • Assign directly to the relevant backing field

EmployeeList is a property. It has only get accessor method - so you can't set it anyway. On the other hand, Manager is a readonly auto property, which is equals to:

class Project
{
        public readonly Employee _Manager;
        public Employee Manager 
        {
            get { return _Manager; }
        }

        // ...

        //Initializes class-variables.
        public Project(Employee manager, EmployeeList 
                        employeeList)
        {
            _Manager = manager;
            // Manager = manager; //Error: Manageris read-only
        }
}

So, when you set Manager , you implicitly set its compiler-defined field ( _Manager in this example ), which is readonly. But the property Manager (and EmployeeList ) can't be setted by the constructor - it's a property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM