IList <T>. AsReadOnly Extension Method Does Not Work for Reference Collection Type

Here is a sample code: The Readonly extension does not work to collect a reference type. if I change Employee to a string, then it will work. Can anyone explain why I get this behavior.

List<Employee> Emps = new List<Employee>(2) { new Employee(){EmpName="E1",Year=2012,EmpID=1}, new Employee(){EmpName="E2",Year=2012,EmpID=2} }; Emps.ForEach(emp => Debug.WriteLine(emp.EmpName)); **IList<Employee> readonlyEmp = Emps.AsReadOnly(); readonlyEmp[0].EmpName = "EMPUpdated";** foreach (var emp in readonlyEmp) { Debug.WriteLine(emp.EmpName); } 
+4
source share
1 answer

A ReadOnlyCollection prevents link modifications to collections. It does not prevent modifications to these objects. If you have ReadOnlyCollection<string> , you cannot change anything because string is immutable. Your Employee class has changed and is subject to change.

Thus, the obvious solution would be to make Employee immutable. Make readonly properties and initialize them in the constructor.

+9
source

Source: https://habr.com/ru/post/1398981/


All Articles