I really don't know how this happens in the internal memory / processor.
I created a class called Block that has a position. In addition, I have a List<Block> for storing my blocks.
First, I add a block to this list:
blocks.Add(new Block());
Then I want to clone this block, so that I have two independent blocks with different positions in my list:
Block clonedBlock = blocks[0]; blocks.Add(clonedBlock);
But when I change the position of the newly created block, I also change the first.
Why is he doing this and is there a way to prevent this?
And by the way, I noticed that lists have some weird behaviors. For example, in this case:
List<Block> list01 = new List<Block>(); [... add some blocks to that list ...] List<Block> list02 = list01;
This made me guess that the lists only contain something like a pointer, and when I try to "clone" a block, I copy only the pointer, but the position indicating that it remains unchanged. The same question: is there a way to prevent this?
Edit: Solution: Object.MemberwiseClone () - Method
source share