Difficulties with managing list items

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; // also tried: List<Block> list02 = list01.ToList(); [... change item in list01 ...] --> also changes that item in list02 

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

+4
source share
1 answer

Your hunch is essentially correct. Classes are reference types, so your line is Block clonedBlock = blocks [0]; sets clonedBlock to the same address as blocks [0]. Any changes made to one will be reflected in the other. You better create a new instance of the block and add it to the list, unless there are reasons why you want to copy another block and just change its position.

One way to do this is to implement a deep copy (I think this term is years since I did something in C ++). Create a new block instance, and then copy the values ​​from the original to the new one.

You can look at the implementation of ICloneable or just write your own copy method (in fact, if you implement ICloneable, you still write your own copy method - the interface simply ensures that classes using it implement the Clone method. Deep or shallow to the performer) .

Also consider the Object.MemberwiseClone method. Object.MemberwiseClone performs a shallow copy, but there is an example of how to perform both shallow and deep copies in the "Examples" section.

+3
source

Source: https://habr.com/ru/post/1483900/


All Articles