I have the following classes:
public class DrawableComplexEntity2D
{
public List<GameComponent> Components { get; set; }
// anothers properties, constructor, methods...
}
public class BoardCell : DrawableComplexEntity2D
{
public GoalPersonGroup GoalPersonGroup { get; set; }
public void CreateGoalPersonGroup(Goal groupType)
{
this.GoalPersonGroup = new GoalPersonGroup(groupType)
base.Components.Add(this.GoalPersonGroup);
}
}
So, when i do:
BoardCell cell1 = new BoardCell();
cell1.CreateGoalPersonGroup(Goal.Type1);
BoardCell cell2 = new BoardCell();
cell2.CreateGoalPersonGroup(Goal.Type2);
cell1.GoalPersonGroup = cell2.GoalPersonGroup;
When i update the cell1.GoalPersonGroup with cell2.GoalPersonGroup, the cell1.GoalPersonGroup is updated, but the cell1.GoalPersonGroup that is inside of the base.Components of cell1 doesn`t change and still the value of cell1 instead cell2. Why?
Lists, as with all other variables, contain values. With a reference type (which I’m assuming
GoalPersonGroupis), the value is a reference. If I have the following:All I’ve done is take the value of
b(which is a reference) and copied that value toa. In the case of a reference type, I can perform operations on that value (like callinga.SomeProperty = "foo";) and those same changes in state will be reflected anywhere in the program where that particular reference is stored in a variable. In other words, if I were to inspect the value ofb.SomeProperty, it would be"foo".However, changing the value in the variable does not affect other variables that point to that value (except in the case of a
refparameter).You’ve added a value that points to a reference to your
List. You’ve also assigned that same value to a property. These two distinct memory locations contain the same value, and thus point to the same actual object. But later you’re just reassigning the value of the property, which means that it now has a different value than what’s stored in the list.