Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IList<T>.AsReadOnly extension method Not working for Reference type Collection

Tags:

c#

readonly

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);
        }
like image 584
mahalingam Avatar asked Jan 18 '23 08:01

mahalingam


1 Answers

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.

like image 129
Henrik Avatar answered Jan 19 '23 22:01

Henrik