Here is the sample code: Readonly extension not working for reference type collection. if I would change the Employee to string then it will work. Could somebody explain why I am getting this behaviour.
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);
}
A ReadOnlyCollection
prevents modifications of the references in the collection. It does not prevent modifications to the referred objects. If you have a ReadOnlyCollection<string>
, you cannot change anything, because string
is immutable. Your Employee
class is mutable and can be changed.
So the obvious solution would be to make Employee
immutable. Make the properties readonly and initialize them in the constructor.
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