Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I use initializer syntax with readonly properties [duplicate]

Tags:

c#

I have a Manager class with two properties as below:

public class Manager()
{
  private string _name;
  private List<int> _reportingEmployeesIds;
  public string Name { get { return _name; }}
  public List<int> ReportingEmployeesIds { get {return _reportingEmployeesIds; } }  

I am trying to create an instance of the Manager class as follows

Manager m = new Manager 
{  
   Name = "Dave", // error, expected
   ReportingEmployeesIds = {2345, 432, 521} // no compile error - why?
};

The set property is missing from both the properties but the compiler allows setting ReportingEmployeesIds whereas does not allow setting the Name property (Error: Property or indexer Manager.Name can not be assigned to, it is readonly).

Why is this the case? Why doesn't the compiler complain about the ReportingEmployeesIds being readonly.

like image 242
Rachel Avatar asked Dec 24 '22 08:12

Rachel


1 Answers

The ReportingEmployeesIds = {2345, 432, 521} doesn't set the property. It is shorthand for calling Add(...) with each of the items. You can always Add, even for a readonly list property.

For it to be a set it would need to be:

ReportingEmployeesIds = new List<int> {2345, 432, 521}

Instead, the line:

Manager m = new Manager {Name = "Dave", ReportingEmployeesIds = {2345, 432, 521} }

is essentially:

var m = new Manager();
m.Name = "Dave";
var tmp = m.ReportingEmployeesIds;
tmp.Add(2345);
tmp.Add(432);
tmp.Add(521);
like image 172
Marc Gravell Avatar answered May 14 '23 07:05

Marc Gravell