Isabella Riquetti Isabella Riquetti - 4 months ago 6
C# Question

When adding a new object to the list all the objects already added previously are overwritten

This is the list that must reference the open classes.

readonly List<object> openedClasses = new List<object>();


Here is where I create classes and add the list.

var employees = myWs.ReturnListEmployee(guid);
foreach (Api.EmployeeData employee in employees)
{
openedClasses.Add(new MyClass(pendingSchedules[0], employee));
}


My class and its constructor:

class MyClass
{
public Schedule schedule;

public MyClass(Schedule schedule, Api.EmployeeData employee)
{
// the "schedule.EmployeeData" it is constantly changed
this.schedule = schedule;
this.schedule.EmployeeData = employee;
}
}


My problem is: Every foreach loop all values previously added to the list are overwritten by the most recently added class.

I've tried all the solutions I found on the internet and made the checks, the class is not static and I removed each static method and static field that was called on it (just to make sure), the list I have created with and without the readonly as list of "object" and as a list of "MyClass".

With:

openedClasses.Add(new MyClass(pendingSchedules[0], employee));


And with:

var myClass = new MyClass(pendingSchedules[0], employee);
openedClasses.Add(myClass);

Answer

So you are looping and calling:

new MyClass(pendingSchedules[0], employee)

Passing the same object pendingSchedules[0] around. In the constructor you are doing this:

this.schedule.EmployeeData = employee;

where this.schedule is the same object reference pendingSchedules[0]

And you are changing it's employee each time but the reference stays the same

You may just want to create a Clone method on Schedule so that you create a new reference each time from the same reference and put the employee on that:

class Schedule
{
    public Schedule Clone()
    {
        return new Schedule
        {
             ValueType1 = this.ValueType1
        }
    }
}

Note: the idea of clone is to break the references, so make sure that any objects you wish to assign to the new Schedule reference are broken in a similar fashion. This is why I say ValueType, because there aren't references associated with them. So string, int, long etc can just be copied like above.

Now you can do this:

public MyClass(Schedule schedule, Api.EmployeeData employee)
{
    this.schedule = schedule.Clone();
    this.schedule.EmployeeData = employee;
}