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.
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);
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